上篇已经搭建好基础demo,接下来继续构建项目并对spring cloud组件介绍描述。
Eureka:实际上在整个过程中维护者每个服务的生命周期。每一个服务都要被注册到Eureka服务器上,这里被注册到Eureka的服务又称为Client。Eureka通过心跳来确定服务是否正常。Eureka只做请求转发。同时Eureka是支持集群的呦!!!
Zuul:类似于网关,反向代理。为外部请求提供统一入口。
Ribbon/Feign:可以理解为调用服务的客户端。
Hystrix:断路器,服务调用通常是深层的,一个底层服务通常为多个上层服务提供服务,那么如果底层服务失败则会造成大面积失败,Hystrix就是就调用失败后触发定义好的处理方法,从而更友好的解决出错。也是微服务的容错机制。
此为eureka的结构图
上篇已注册了user,movie的服务,接下来用Ribbo,feign实现负载均衡和web service的简单客户端,让movie消费者调用user服务。
Ribbon:
Ribbon 是 Netflix 发布的云中间层服务开源项目,其主要功能是提供客户侧软件负载均衡算法,将 Netflix 的中间层服务连接在一起。Eureka 是一个 RESTful 服务,用来定位运行在 AWS 域(Region)中的中间层服务。本文介绍 Eureka 和 Ribbon 的集成,附带 Ribbon 自定义负载均衡算法示例。
Feign:
在Spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client, Spring的RestTemplate。Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,非常快捷简便。
这是movie服务的目录结构按此新建java文件
pom加入新依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
Ribbon的负载均衡可以通过注解调用
也可以自定义configration 负载均衡的算法,但是不能和Application同目录
public class RibbonConfiguration {
@Autowired
private IClientConfig ribbonClientConfig;
/**
* Our IPing is a PingUrl, which will ping a URL to check the status of each
* server.provider has, as you’ll recall, a method mapped to the / path;
* that means that Ribbon will get an HTTP 200 response when it pings a
* running provider server.
*
* server list defined in application.yml :listOfServers: localhost:8000,
* localhost:8002,localhost:8003
*
*/
@Bean
public IPing ribbonPing(IClientConfig config) {
// ping url will try to access http://microservice-provider/provider/ to
// see if reponse code is 200 . check PingUrl.isAlive()
// param /provider/ is the context-path of provider service
return new PingUrl(false, "/provider/");
}
/**
* The IRule we set up, the AvailabilityFilteringRule, will use Ribbon’s
* built-in circuit breaker functionality to filter out any servers in an
* “open-circuit” state: if a ping fails to connect to a given server, or if
* it gets a read failure for the server, Ribbon will consider that server
* “dead” until it begins to respond normally.
*
* AvailabilityFilteringRule | 过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值) | 使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态
* RandomRule | 随机选择一个server
* BestAvailabl eRule | 选择一个最小的并发请求的server | 逐个考察Server,如果Server被tripped了,则忽略,在选择其中
* RoundRobinRule | roundRobin方式轮询选择 | 轮询index,选择index对应位置的server
* WeightedResponseTimeRule | 根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。 | 一 个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成statas时,使用roubine策略选择 server。
* RetryRule | 对选定的负载均衡策略机上重试机制。 | 在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的server
* ZoneAvoidanceRule | 复合判断server所在区域的性能和server的可用性选择server | 使 用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个 zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的 Server。
* @param config
* @return
*/
@Bean
public IRule ribbonRule(IClientConfig config) {
// return new AvailabilityFilteringRule();
return new RandomRule();//
// return new BestAvailableRule();
// return new RoundRobinRule();//轮询
// return new WeightedResponseTimeRule();
// return new RetryRule();
// return new ZoneAvoidanceRule();
}
}
可以在controller输出看ribbon的负载是否实现
接下来 ,配置feign,知识feign的config
@Configuration
public class FeignConfig {
@Bean
public Contract feignContract(){
return new feign.Contract.Default();
}
}
定义feign的客户端接口,这里调用user 微服务的接口,feign支持springMvc注解,但要生明请求方法和参数
@FeignClient(name="userprovider",configuration = FeignClient.class)
public interface UserFeignClient {
@RequestMapping (value = "/user/{id}",method = RequestMethod.GET)
public User find(@PathVariable("id") int id);
}
然后在application里添加feign注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class MicroserviceSimpleConsumerMovieApplication {
public static void main(String[] args) {
// @Bean
// public RestTemplate restTemplate(){
// return new RestTemplate();
// }
SpringApplication.run(MicroserviceSimpleConsumerMovieApplication.class, args);
}
}
最后controller测试feign的接口
@RestController
public class NewsController {
@Autowired
RestTemplate restTemplate;
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
UserFeignClient userFeignClient;
@RequestMapping("/newsUser/{id}")
public User find(@PathVariable int id){
return restTemplate.getForObject("http://localhost:8080/user/"+id,User.class);
}
@GetMapping("/test")
public String test(){
ServiceInstance serviceInstance=loadBalancerClient.choose("userprovider");
String s=serviceInstance.getHost()+serviceInstance.getPort()+serviceInstance.getServiceId();
return s;
}
@GetMapping("/movie/{id}")
public User findmovie(@PathVariable int id){
return userFeignClient.find(id);
}
}
分别启动eureka,user和movie微服务
访问movie的测试接口,成功返回数据
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。