SpringCloud入门(一)

1. 系统架构演变概述

集中式架构
垂直拆分
分布式服务
SOA面向服务架构
微服务架构

2. 微服务架构说明

SOA使用了ESB组件的面向服务架构:ESB自身实现复杂;应用服务粒度较大,所有服务之间的通信都经过ESB会降低通信速度;部署、测试ESB比较麻烦。

微服务架构:是一套使用小服务或者单一业务来开发单个应用的方式或途径。

微服务架构特点:

  • 单一职责
  • 服务粒度小
  • 面向服务(对外暴露REST api)
  • 服务之间相互独立

与使用ESB的SOA架构的区别:微服务架构没有使用ESB,有服务治理注册中心;业务粒度小。

3. 服务调用方式说明

  • RPC:基于socket,速度快,效率高;webservice、dubbo
  • HTTP:基于TCP,封装比较臃肿;对服务和调用方没有任何技术、语言的限定,自由灵活;RESTful,Spring Cloud

4. Spring RestTemplate示例工程导入

一般情况下有如下三种http客户端工具类包都可以方便的进行http服务调用:

  • httpClient
  • okHttp
  • JDK原生URLConnection

spring 提供了RestTemplate的工具类对上述的3种http客户端工具类进行了封装,可在spring项目中使用RestTemplate进行服务调用。

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {@Autowiredprivate RestTemplate restTemplate;@Testpublic void test(){String url = "http://localhost/user/8";//restTemplate可以对json格式字符串进行反序列化User user = restTemplate.getForObject(url, User.class);System.out.println(user);}
}

5. Spring Cloud概述

  • 整合的组件可以有很多组件;常见的组件有:eureka注册中心,Gateway网关,Ribbon负载均衡,Feign服务调用,Hystrix熔断器。在有需要的时候项目添加对于的启动器依赖即可。
  • 版本特征:以英文单词命名(伦敦地铁站名)

6. 创建微服务工程

需求:查询数据库中的用户数据并输出到浏览器

  • 父工程heima-springcloud:添加spring boot父坐标和管理其它组件的依赖
  • 用户服务工程user-service:整合mybatis查询数据库中用户数据;提供查询用户服务
  • 服务消费工程consumer-demo:利用查询用户服务获取用户数据并输出到浏览器

小结

            <!-- springCloud --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency>

通过 scope 的import可以继承 spring-cloud-dependencies 工程中的依赖

7. 搭建配置user-service工程

需求:可以访问http://localhost:9091/user/8输出用户数据

实现步骤:

  1. 添加启动器依赖(web、通用Mapper);
  2. 创建启动引导类和配置文件;
  3. 修改配置文件中的参数;
  4. 编写测试代码(UserMapper,UserService,UserController);
  5. 测试
  • 添加启动器依赖
    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 通用Mapper启动器 --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId></dependency><!-- mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
  • 编写配置文件
server:port: 9091
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/springcloudusername: rootpassword: rootmybatis:type-aliases-package: com.itheima.user.pojo

8. 搭建配置consumer-demo工程

目标:编写测试类使用restTemplate访问user-service的路径根据id查询用户

分析

需求:访问http://localhost:8080/consumer/8 使用RestTemplate获取http://localhost:9091/user/8的数据

实现步骤:

  1. 添加启动器依赖;
  2. 创建启动引导类(注册RestTemplate)和配置文件;
  3. 编写测试代码(ConsumerController中使用restTemplate访问服务获取数据)
  4. 测试
    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
@SpringBootApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Beanpublic RestTemplate get(){return new RestTemplate();}
}
@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")public User get(@PathVariable long id){return restTemplate.getForObject("http://localhost:9091/user/"+id, User.class);}}
  • 服务管理
    如何自动注册和发现
    如何实现状态监管
    如何实现动态路由
  • 服务如何实现负载均衡
  • 服务如何解决容灾问题
  • 服务如何实现统一配置

上述的问题都可以通过Spring Cloud的各种组件解决。

9. Eureka注册中心说明

Eureka的主要功能是进行服务管理,定期检查服务状态,返回服务地址列表。

10. 搭建eureka-server工程

Eureka是服务注册中心,只做服务注册;自身并不提供服务也不消费服务。可以搭建web工程使用Eureka,可以使用Spring Boot方式搭建。

搭建步骤:

  1. 创建工程;
  2. 添加启动器依赖;
  3. 编写启动引导类(添加Eureka的服务注解)和配置文件;
  4. 修改配置文件(端口,应用名称…);
  5. 启动测试

小结

  • 启动器依赖
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>
  • 配置文件
server:port: 10086
spring:application:name: eureka-server
eureka:client:service-url:# eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址defaultZone: http://127.0.0.1:10086/eureka# 不注册自己register-with-eureka: false# 不拉取服务fetch-registry: false

11. 服务注册与发现

  • 服务注册:在服务提供工程user-service上添加Eureka客户端依赖;自动将服务注册到EurekaServer服务地址列表。
    • 添加依赖;
    • 改造启动引导类;添加开启Eureka客户端发现的注解;
    • 修改配置文件;设置Eureka 服务地址
  • 服务发现:在服务消费工程consumer-demo上添加Eureka客户端依赖;可以使用工具类根据服务名称获取对应的服务地址列表。
    • 添加依赖;
    • 改造启动引导类;添加开启Eureka客户端发现的注解;
    • 修改配置文件;设置Eureka 服务地址;
    • 改造处理器类ConsumerController,可以使用工具类DiscoveryClient根据服务名称获取对应服务地址列表。

添加依赖

      <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>

修改配置文件

eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka

服务注册

@SpringBootApplication
@MapperScan("com.gogo.mapper")
@EnableDiscoveryClient
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}
}

服务发现

@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;@GetMapping("/{id}")public User get(@PathVariable long id){List<ServiceInstance> instances = discoveryClient.getInstances("user-service");ServiceInstance serviceInstance = instances.get(0);return restTemplate.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id, User.class);}}

12. Eureka Server高可用配置

分析

Eureka Server是一个web应用,可以启动多个实例(配置不同端口)保证Eureka Server的高可用。

高可用配置:将Eureka Server作为一个服务注册到其它Eureka Server,这样多个Eureka Server之间就能够互相发现对方,同步服务,实现Eureka Server集群。

13. Eureka客户端与服务端配置

配置eureka客户端user-service的注册、续约等配置项,配置eureka客户端consumer-demo的获取服务间隔时间;了解失效剔除和自我保护

  • Eureka客户端工程
    • user-service 服务提供
      • 服务地址使用ip方式
      • 续约
    • consumer-demo 服务消费
      • 获取服务地址的频率
  • Eureka服务端工程 eureka-server
    • 失效剔除
    • 自我保护
  • user-service
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:# 更倾向使用ip地址,而不是host名prefer-ip-address: true# ip地址ip-address: 127.0.0.1# 续约间隔,默认30秒lease-renewal-interval-in-seconds: 5# 服务失效时间,默认90秒lease-expiration-duration-in-seconds: 5
  • consumer-demo
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka# 获取服务地址列表间隔时间,默认30秒registry-fetch-interval-seconds: 10
  • eureka-server
eureka:server:# 服务失效剔除时间间隔,默认60秒eviction-interval-timer-in-ms: 60000# 关闭自我保护模式(默认是打开的)enable-self-preservation: false

15. Ribbon负载均衡应用

分析

需求:可以使用RestTemplate访问http://user-service/user/8获取服务数据。

可以使用Ribbon负载均衡:在执行RestTemplate发送服务地址请求的时候,使用负载均衡拦截器拦截,根据服务名获取服务地址列表,使用Ribbon负载均衡算法从服务地址列表中选择一个服务地址,访问该地址获取服务数据。

实现步骤:

  1. 启动多个user-service实例(9091,9092);
  2. 修改RestTemplate实例化方法,添加负载均衡注解;
  3. 修改ConsumerController;
  4. 测试
@SpringBootApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate get(){return new RestTemplate();}
}
@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;@GetMapping("/{id}")public User get(@PathVariable long id){List<ServiceInstance> instances = discoveryClient.getInstances("user-service");ServiceInstance serviceInstance = instances.get(0);return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, User.class);}}

小结

在实例化RestTemplate的时候使用@LoadBalanced,服务地址直接可以使用服务名。

16. 熔断器Hystrix简介

目标:了解熔断器Hystrix的作用

小结

Hystrix是一个延迟和容错库,用于隔离访问远程服务,防止出现级联失败。

17. 线程隔离&服务降级

Hystrix解决雪崩效应:

  • 线程隔离:用户请求不直接访问服务,而是使用线程池中空闲的线程访问服务,加速失败判断时间。

  • 服务降级:及时返回服务调用失败的结果,让线程不因为等待服务而阻塞。

  • consumer-demo中添加依赖

        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>
  • 开启熔断
@SpringCloudApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate get(){return new RestTemplate();}
}
  • 降级逻辑
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFall")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")
/*    @HystrixCommand(fallbackMethod = "fall")*/@HystrixCommandpublic String get(@PathVariable long id){return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, String.class);}public String fall(long id){log.error("查询{}失败",id);return "网络太差了";}public String defaultFall(){return "默认网络太差了";}}
  • 修改超时配置
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 2000

18. 服务熔断演示

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFall")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")
/*    @HystrixCommand(fallbackMethod = "fall")*/@HystrixCommandpublic String get(@PathVariable long id){
if(id==1) throw new RuntimeException("不行的");return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, String.class);}public String fall(long id){log.error("查询{}失败",id);return "网络太差了";}public String defaultFall(){return "默认网络太差了";}}
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 2000circuitBreaker:errorThresholdPercentage: 50 # 触发熔断错误比例阈值,默认值50%sleepWindowInMilliseconds: 10000 # 熔断后休眠时长,默认值5秒requestVolumeThreshold: 10 # 熔断触发最小请求次数,默认值是20

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391724.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PullToRefreshListView中嵌套ViewPager滑动冲突的解决

PullToRefreshListView中嵌套ViewPager滑动冲突的解决 最近恰好遇到PullToRefreshListView中需要嵌套ViewPager的情况,ViewPager 作为头部添加到ListView中&#xff0c;发先ViewPager在滑动过程中流畅性太差几乎很难左右滑动。在网上也看了很多大神的介绍&#xff0c;看了ViewP…

神经网络 卷积神经网络_如何愚弄神经网络?

神经网络 卷积神经网络Imagine you’re in the year 2050 and you’re on your way to work in a self-driving car (probably). Suddenly, you realize your car is cruising at 100KMPH on a busy road after passing through a cross lane and you don’t know why.想象一下…

数据特征分析-分布分析

分布分析用于研究数据的分布特征&#xff0c;常用分析方法&#xff1a; 1、极差 2、频率分布 3、分组组距及组数 df pd.DataFrame({编码:[001,002,003,004,005,006,007,008,009,010,011,012,013,014,015],\小区:[A村,B村,C村,D村,E村,A村,B村,C村,D村,E村,A村,B村,C村,D村,E村…

开发工具总结(2)之全面总结Android Studio2.X的填坑指南

前言&#xff1a;好多 Android 开发者都在说Android Studio太坑了&#xff0c;老是出错&#xff0c;导致开发进度变慢&#xff0c;出错了又不知道怎么办&#xff0c;网上去查各种解决方案五花八门&#xff0c;有些可以解决问题&#xff0c;有些就是转来转去的写的很粗糙&#x…

无聊的一天_一人互联网公司背后的无聊技术

无聊的一天Listen Notes is a podcast search engine and database. The technology behind Listen Notes is actually very very boring. No AI, no deep learning, no blockchain. “Any man who must say I am using AI is not using True AI” :)Listen Notes是一个播客搜索…

如何在Pandas中使用Excel文件

From what I have seen so far, CSV seems to be the most popular format to store data among data scientists. And that’s understandable, it gets the job done and it’s a quite simple format; in Python, even without any library, one can build a simple CSV par…

Js实现div随鼠标移动的方法

HTML: <div id"odiv" style" COLOR: #666; padding: 2px 8px; FONT-SIZE: 12px; MARGIN-RIGHT: 5px; position: absolute; background: #fff; display: block; border: 1px solid #666; top: 50px; left: 10px;"> Move_Me</div>第一种&…

leetcode 867. 转置矩阵

给你一个二维整数数组 matrix&#xff0c; 返回 matrix 的 转置矩阵 。 矩阵的 转置 是指将矩阵的主对角线翻转&#xff0c;交换矩阵的行索引与列索引。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 输出&#xff1a;[[1,4,7],[2,5,8],[3,6,9]] …

数据特征分析-对比分析

对比分析是对两个互相联系的指标进行比较。 绝对数比较(相减)&#xff1a;指标在量级上不能差别过大&#xff0c;常用折线图、柱状图 相对数比较(相除)&#xff1a;结构分析、比例分析、空间比较分析、动态对比分析 df pd.DataFrame(np.random.rand(30,2)*1000,columns[A_sale…

Linux基线合规检查中各文件的作用及配置脚本

1./etc/motd 操作&#xff1a;echo " Authorized users only. All activity may be monitored and reported " > /etc/motd 效果&#xff1a;telnet和ssh登录后的输出信息 2. /etc/issue和/etc/issue.net 操作&#xff1a;echo " Authorized users only. All…

tableau使用_使用Tableau升级Kaplan-Meier曲线

tableau使用In a previous article, I showed how we can create the Kaplan-Meier curves using Python. As much as I love Python and writing code, there might be some alternative approaches with their unique set of benefits. Enter Tableau!在上一篇文章中 &#x…

踩坑 net core

webclient 可以替换为 HttpClient 下载获取url的内容&#xff1a; 证书&#xff1a; https://stackoverflow.com/questions/40014047/add-client-certificate-to-net-core-httpclient 转载于:https://www.cnblogs.com/zxs-onestar/p/7340386.html

我从参加#PerfMatters会议中学到的东西

by Stacey Tay通过史黛西泰 我从参加#PerfMatters会议中学到的东西 (What I learned from attending the #PerfMatters conference) 从前端的网络运行情况发布会上的注意事项 (Notes from a front-end web performance conference) This week I had the privilege of attendin…

修改innodb_flush_log_at_trx_commit参数提升insert性能

最近&#xff0c;在一个系统的慢查询日志里发现有个insert操作很慢&#xff0c;达到秒级&#xff0c;并且是比较简单的SQL语句&#xff0c;把语句拿出来到mysql中直接执行&#xff0c;速度却很快。 这种问题一般不是SQL语句本身的问题&#xff0c;而是在具体的应用环境中&#…

leetcode 1178. 猜字谜(位运算)

外国友人仿照中国字谜设计了一个英文版猜字谜小游戏&#xff0c;请你来猜猜看吧。 字谜的迷面 puzzle 按字符串形式给出&#xff0c;如果一个单词 word 符合下面两个条件&#xff0c;那么它就可以算作谜底&#xff1a; 单词 word 中包含谜面 puzzle 的第一个字母。 单词 word…

Nexus3.x.x上传第三方jar

exus3.x.x上传第三方jar&#xff1a; 1. create repository 选择maven2(hosted)&#xff0c;说明&#xff1a; proxy&#xff1a;即你可以设置代理&#xff0c;设置了代理之后&#xff0c;在你的nexus中找不到的依赖就会去配置的代理的地址中找hosted&#xff1a;你可以上传你自…

责备的近义词_考试结果危机:我们应该责备算法吗?

责备的近义词I’ve been considering writing on the topic of algorithms for a little while, but with the Exam Results Fiasco dominating the headline news in the UK during the past week, I felt that now is the time to look more closely into the subject.我一直…

电脑如何设置终端设置代理_如何设置一个严肃的Kubernetes终端

电脑如何设置终端设置代理by Chris Cooney克里斯库尼(Chris Cooney) 如何设置一个严肃的Kubernetes终端 (How to set up a serious Kubernetes terminal) 所有k8s书呆子需要的CLI工具 (All the CLI tools a growing k8s nerd needs) Kubernetes comes pre-packaged with an ou…

spring cloud(二)

1. Feign应用 Feign的作用&#xff1b;使用Feign实现consumer-demo代码中调用服务 导入启动器依赖&#xff1b;开启Feign功能&#xff1b;编写Feign客户端&#xff1b;编写一个处理器ConsumerFeignController&#xff0c;注入Feign客户端并使用&#xff1b;测试 <dependen…

c/c++编译器的安装

MinGW(Minimalist GNU For Windows)是个精简的Windows平台C/C、ADA及Fortran编译器&#xff0c;相比Cygwin而言&#xff0c;体积要小很多&#xff0c;使用较为方便。 MinGW最大的特点就是编译出来的可执行文件能够独立在Windows上运行。 MinGW的组成&#xff1a; 编译器(支持C、…