1.关于eureka服务之间的调用常见的方式是使用feign或者是restTemplate
feign是声明式的rest客户端,并整合了ribbon负载均衡和hystrix的熔断降级处理
这里讲的是ribbon的负载均衡
顶级的两个接口为
ILoadBlancer 负载均衡器
IRule 均衡策略
详细的不在描述,均衡策略有
com.netflix.loadbalancer.RandomRule 随机策略
RoundRobinRule 线性轮询策略 ribbon默认的均衡策略就是这个
RetryRule 重试策略等等
在配置文件中指定负载均衡策略,例如在application.yml增加如下配置
#制定负载均和策略
appuser:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
其中appuser为服务名,表示在请求appuser服务的时候,在eureka有多个appuser的服务,具体请求到哪个服务采用随机策略
2.简单介绍两种调用服务的方式
feign的方式
@FeignClient(name = "appuser",fallback=UserClientFallBack.class)
public interface UserClient {
@RequestMapping(value="/v1/user/test",method = RequestMethod.GET)
String callUserTest() throws Exception;
}
restTemplate的方式
//使用restTempalte调用 微服务名 appuesr为微服务名, 有负载均的效果(轮询的方式) 但没有断路器的重试的机制
//即由于eureka的自我保护策略,非正常下线的服务还在注册中心,使用轮询的方式会反问到已经下线的服务,使
//restTemplate 不会去熔断和重试 而使用 feign调用的话会重试
@RequestMapping(value = "/ribbon-consumer",method = RequestMethod.GET)
public String helloController() {
return restTemplate.getForEntity("http://appuser/v1/user/test", String.class).getBody();
}
其中关于RestTemplate的配置,要使用 @LoadBalanced注解
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}