1.1 注册中心 (1)Eureka
搭建注册中心 引入依赖 spring-cloud-starter-netflix-eureka-server
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>配置 EurekaServer
eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/通过 @EnableEurekaServer 激活Eureka Server端配置
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }服务注册 服务提供者引入 spring -cloud-starter-netflix-eureka-client 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>通过 eureka.client.serviceUrl.defaultZone 配置注册中心地址
eureka: client: serviceUrl: # eureka server的路径 defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true #使用ip注册 @SpringBootApplication //@EnableDiscoveryClient //@EnableEurekaClient public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }(2)consul
简介
Consul 使用 Go 语言编写,使用 Raft 算法来保证一致性,支持健康检查,支持 http 和 dns 协议接口。
搭建注册中心 下载安装 consul 启动 consul consul agent -dev
服务注册 服务提供者引入 spring -cloud-starter-consul-discovery 依赖
<!--SpringCloud提供的基于Consul的服务发现--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!--actuator用于心跳检查--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>通过 spring.cloud.consul.host 和 spring.cloud.consul.port 指定Consul Server的请 求地址
spring: ...省略 cloud: consul: #consul相关配置 host: 192.168.74.101 #ConsulServer请求地址 port: 8500 #ConsulServer端口 discovery: #是否注册 register: true #实例ID instance-id: ${spring.application.name}-1 #服务实例名称 service-name: ${spring.application.name} #服务实例端口 port: ${server.port} #健康检查路径 healthCheckPath: /actuator/health #健康检查时间间隔 healthCheckInterval: 15s #开启ip地址注册 prefer-ip-address: true #实例的请求ip ip-address: ${spring.cloud.client.ip-address}(3)consul与Eureka的区别
一致性 Consul强一致性(CP) 服务注册相比Eureka会稍慢一些。因为Consul的raft协议要求必须过半数的节点都写入成功才认 为注册成功 Leader挂掉时,重新选举期间整个consul不可用。保证了强一致性但牺牲了可用性。 Eureka保证高可用和最终一致性(AP) 服务注册相对要快,因为不需要等注册信息replicate到其他节点,也不保证注册信息是否 replicate成功 当数据出现不一致时,虽然A, B上的注册信息不完全相同,但每个Eureka节点依然能够正常对外提 供服务,这会出现查询服务信息时如果请求A查不到,但请求B就能查到。如此保证了可用性但牺 牲了一致性。开发语言和使用 eureka就是个servlet程序,跑在servlet容器中 Consul则是go编写而成,安装启动即可(1)Ribbon
简介
Eureka一般配合Ribbon进行使用,Ribbon提供了客户端负载均衡的功能,Ribbon利用从Eureka中读 取到的服务信息,在调用服务节点提供的服务时,会合理的进行负载。
在SpringCloud中可以将注册中心和Ribbon配合使用,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务
作用
(1)服务调用
基于Ribbon实现服务调用, 是通过拉取到的所有服务列表组成(服务名-请求
路径的)映射关系。借助 RestTemplate 最终进行调用
(2)负载均衡
当有多个服务提供者时,Ribbon可以根据负载均衡的算法自动的选择需要调用的服务地址
通过 Ribbon结合RestTemplate方式进行服务调用只需要在声明RestTemplate的方法上添加注解 @LoadBalanced即可
/** * 使用spring提供的RestTemplate发送http请求到商品服务 * 1.创建RestTemplate对象交给容器管理 * 2.在使用的时候,调用其方法完成操作 (getXX,postxxx) * * @LoadBalanced : 是ribbon提供的负载均衡的注解 */ @LoadBalanced @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } @Autowired private RestTemplate restTemplate; @GetMapping("/buy/{id}") public Product order() { //通过restTemplate调用商品微服务 //Product product = restTemplate.getForObject("http://127.0.0.1:9002/product/1", Product.class); Product product = restTemplate.getForObject("http://shop-service- product/product/1", Product.class); return product; }可以通过 { 服务名称}.ribbon.NFLoadBalancerRuleClassName 配置负载均衡策略
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ubrEFimq-1602131739964)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1601978081713.png)]
#修改ribbon的负载均衡策略 服务名 - ribbon - NFLoadBalancerRuleClassName : 策略 service-product: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置负载均衡策略 ConnectTimeout: 250 # Ribbon的连接超时时间 ReadTimeout: 1000 # Ribbon的数据读取超时时间 OkToRetryOnAllOperations: true # 是否对所有操作都进行重试 MaxAutoRetriesNextServer: 1 # 切换实例的重试次数 MaxAutoRetries: 1 # 对当前实例的重试次数(2)Feign
简介
Feign是Netflix开发的声明式,模板化的HTTP客户端,其灵感来自Retrofit,JAXRS-2.0以及WebSocket. Feign可帮助我们更加便捷,优雅的调用HTTP API。 在SpringCloud中,使用Feign非常简单——创建一个接口,并在接口上添加一些注解,代码就完 成了。 Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。 SpringCloud对Feign进行了增强,使Feign支持了SpringMVC注解,并整合了Ribbon和Eureka, 从而让Feign的使用更加方便。
服务消费者引入 spring-cloud-starter-openfeign 依赖
<!--springcloud整合的openFeign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>通过 @FeignClient 声明一个调用远程微服务接口
** * 声明需要调用的微服务名称 * @FeignClient * * name : 服务提供者的名称 */ @FeignClient(name="service-product") public interface ProductFeignClient { /** * 配置需要调用的微服务接口 */ @RequestMapping(value="/product/{id}",method = RequestMethod.GET) public Product findById(@PathVariable("id") Long id); }添加ProductFeginClient的自动注入,并在order方法中使用ProductFeginClient 完成微服务调用
@RestController @RequestMapping("/order") public class OrderController { @Autowired private ProductFeginClient productFeginClient; @GetMapping("/buy/{id}") public Product order(@PathVariable Long id) { return productFeginClient.findById(id); } }启动类上通过 @EnableFeignClients 激活Feign
@EnableFeignClients public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); } }Feign支持如下配置项
feign: client: config: feignName: ##定义FeginClient的名称 需要调用的服务名称 connectTimeout: 5000 # 相当于Request.Options readTimeout: 5000 # 相当于Request.Options # 配置Feign的日志级别,相当于代码配置方式中的Logger #配置feign日志的输出 # 日志配置 NONE : 不输出日志(高) BASIC: 适用于生产环境追踪问题 # HEADERS : 在BASIC的基础上,记录请求和响应头信息 FULL : 记录所有 loggerLevel: full # Feign的错误解码器,相当于代码配置方式中的ErrorDecoder errorDecoder: com.example.SimpleErrorDecoder # 配置重试,相当于代码配置方式中的Retryer retryer: com.example.SimpleRetryer # 配置拦截器,相当于代码配置方式中的RequestInterceptor requestInterceptors: - com.example.FooRequestInterceptor - com.example.BarRequestInterceptor decode404: falseSpring Cloud Feign 支持对请求和响应进行GZIP压缩
feign: compression: request: enabled: true # 开启请求压缩 mime-types: text/html,application/xml,application/json # 设置压缩的数据类型 ,非必须 min-request-size: 2048 # 设置触发压缩的大小下限,非必须 response: enabled: true # 开启响应压缩开启日志级别
logging: level: cn.itcast.order.fegin.ProductFeginClient: debug #feign微服务调用接口的类路径