說明
服務注冊在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();
}
- 書寫服務
@Service
public 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
@EnableFeignClients
public 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.DefaultClientConfigImpl
IRule ribbonRule: com.netflix.loadbalancer.ZoneAvoidanceRule
IPing ribbonPing: com.netflix.loadbalancer.NoOpPing
ServerList<Server> ribbonServerList: com.netflix.loadbalancer.ConfigurationBasedServerList
ServerListFilter<Server> ribbonServerListFilter: org.springframework.cloud.netflix.ribbon.ZonePreferenceServerListFilter
ILoadBalancer 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
- 定制負載均衡策略
對某個服務指定特定的負載均衡策略
@Configuration
public 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=true
feign.compression.response.enabled=true
#支持壓縮的mime types
feign.compression.request.enabled=true
feign.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: SpringEncoder
Logger feignLogger: Slf4jLogger
Contract feignContract: SpringMvcContract
Feign.Builder feignBuilder: HystrixFeign.Builder
Spring Cloud Netflix沒有提供默認值,但仍然可以在feign上下文配置中創建
Logger.Level
Retryer
ErrorDecoder
Request.Options
Collection<RequestInterceptor>
一個具體的Feign擴展配置類
@Configuration
public 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