Spring cloud实践之道三(服务消费和负载均衡)
说明
服务注册在eureka服务器上,服务与服务的通讯是基于http restful的。spring cloud有两种消费服务的方式
ribbon+restTemplate
feign
这一章我们将一起看一下如下进行服务的消费
演示用例:启动多个eurekaClient,消费演示例子eurekaCustomer
Ribbon + RestTemplate的方式
修改pom.xml文件,增加ribbon的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency>
增加restTemplate的注入bean
@Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }
书写服务
@Servicepublic class HelloService { // 待消费服务的名字 private static final String SERVICE_NAME = "EUREKACLIENT"; @Autowired RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; public String helloService(String name) { ServiceInstance serviceInstance = this.loadBalancerClient.choose(SERVICE_NAME); System.out.println("服务主机:" + serviceInstance.getHost()); System.out.println("服务端口:" + serviceInstance.getPort()); // 通过服务名来访问 return restTemplate.getForObject("http://" + SERVICE_NAME + "/hello?name="+name,String.class); } }
Feign的方式
修改pom.xml文件,增加feign的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
启动类添加注解:@EnableFeignClients
@SpringBootApplication@EnableDiscoveryClient@EnableFeignClientspublic class EurekaCustomer { public static void main(String[] args) { SpringApplication.run(EurekaCustomer.class, args); } }
增加feign服务
@FeignClient(value="EUREKACLIENT")public interface FeignService { @RequestMapping(value = "/hello",method = RequestMethod.GET) String sayHiUseFeign(@RequestParam(value = "name") String name); }
负载均衡
Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。Ribbon客户端组 件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随即连接等)去连接这些机器。我们也很容易使用Ribbon实现 自定义的负载均衡算法。
在Spring Cloud中,通过Ribbon进行负载均衡,Feign也用到Ribbon,当你使用@FeignClient,Ribbon自动被应用。
通常利用@LoadBalanced来让RestTemplate具备客户端负载功能
Ribbon架构图
来自网络,Ribbon架构图
Spring Cloud提供的负载均衡策略
简单轮询负载均衡(RoundRobin)
随机负载均衡 (Random)
加权响应时间负载均衡 (WeightedResponseTime)
区域感知轮询负载均衡(ZoneAware)
负载均衡策略比较
负载均衡策略比较,来自网络
Spring Cloud中Ribbon默认提供的Bean:(BeanType beanName: ClassName)
IClientConfig ribbonClientConfig: com.netflix.client.config.DefaultClientConfigImplIRule ribbonRule: com.netflix.loadbalancer.ZoneAvoidanceRuleIPing ribbonPing: com.netflix.loadbalancer.NoOpPingServerList<Server> ribbonServerList: com.netflix.loadbalancer.ConfigurationBasedServerListServerListFilter<Server> ribbonServerListFilter: org.springframework.cloud.netflix.ribbon.ZonePreferenceServerListFilterILoadBalancer ribbonLoadBalancer: com.netflix.loadbalancer.ZoneAwareLoadBalancer
负载均衡的配置参数
# 该参数用来开启重试机制,它默认是关闭的spring.cloud.loadbalancer.retry.enabled=true# 断路器的超时时间需要大于ribbon的超时时间,不然不会触发重试。hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000# 请求连接的超时时间hello-service.ribbon.ConnectTimeout=250# 请求处理的超时时间hello-service.ribbon.ReadTimeout=1000# 对所有操作请求都进行重试hello-service.ribbon.OkToRetryOnAllOperations=true# 切换实例的重试次数hello-service.ribbon.MaxAutoRetriesNextServer=2# 对当前实例的重试次数hello-service.ribbon.MaxAutoRetries=1
定制负载均衡策略
对某个服务指定特定的负载均衡策略
@Configurationpublic class HelloConfiguration { /** * 负载均衡策略 * @return */ @Bean public IRule ribbonRule() {// return new BestAvailableRule(); //选择一个最小的并发请求的server// return new WeightedResponseTimeRule(); //根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。// return new RetryRule(); //对选定的负载均衡策略机上重试机制。// return new RoundRobinRule(); //roundRobin方式轮询选择server return new RandomRule(); //随机选择一个server// return new ZoneAvoidanceRule(); //复合判断server所在区域的性能和server的可用性选择server// return new AvailabilityFilteringRule(); } }
Feign的配置信息
#Hystrix支持,如果为true,hystrix库必须在classpath中feign.hystrix.enabled=false#请求和响应GZIP压缩支持feign.compression.request.enabled=truefeign.compression.response.enabled=true#支持压缩的mime typesfeign.compression.request.enabled=truefeign.compression.request.mime-types=text/xml,application/xml,application/json feign.compression.request.min-request-size=2048# 日志支持logging.level.project.user.UserClient: DEBUG
Feign的自定义
Spring Cloud Netflix 提供了默认的Bean类型
Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)Encoder feignEncoder: SpringEncoderLogger feignLogger: Slf4jLoggerContract feignContract: SpringMvcContractFeign.Builder feignBuilder: HystrixFeign.Builder
Spring Cloud Netflix没有提供默认值,但仍然可以在feign上下文配置中创建
Logger.LevelRetryerErrorDecoderRequest.OptionsCollection<RequestInterceptor>
一个具体的Feign扩展配置类
@Configurationpublic class FeignConfiguration { @Bean @Scope("prototype") public Feign.Builder feignBuilder() { return Feign.builder(); } @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } }
使用Feign扩展配置
@FeignClient(value="EUREKACLIENT", configuration=FeignConfiguration.class)public interface FeignService { @RequestMapping(value = "/hello",method = RequestMethod.GET) String sayHiUseFeign(@RequestParam(value = "name") String name); }
Paste_Image.png
作者:hutou
链接:https://www.jianshu.com/p/0833b5adb722
共同学习,写下你的评论
评论加载中...
作者其他优质文章