用到的组件
- Eureka 服务注册与发现
- Ribbon 客户端负载均衡
- Feign 远程调用(HTTP方式)
- spring cloud config 统一配置
- Bus 自动更新配置
- RabbitMQ 消息队列
- spring cloud Stream
- Zuul 网关
- Hystrix 断路器
- Docker 容器部署
- Rancher 部署私有镜像
- graylog
Stream
说到异步就不得不说MQ(消息队列),而Stream就是封装在消息队列上的框架,Stream集成了RabbitMQ和Kafka,我这里以Rabbit MQ讲解。好了,Let's begin.
什么叫异步?
异步就是客户端发消息给服务器,服务器不会即时响应。
消息队列(RabbitMQ)
rabbitMQ的作用是异步处理,把客户端发起的请求放入消息队列中,然后服务器从消息队列中一一读取,进行处理。
rabbitMQ的基本用法
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 消息接收
方法一 :手动在RabbitMQ上创建队
@RabbitListener(queues = "队列的名字,如MyQueue")
public void receiver(){
}
方法二 :自动创建队列
@RabbitListener(queuesToDeclare = "MyQueue")
public void receiver(){
}
方法三: 绑定队列与exchange
@RabbitListener(bingdings = @QueueBingding(
value = @Queue("MyQueue")
exchange = @Exchange("MyExchange")))
public void receiver(){
}
-
消息发送
使用类AmqpTemplate的方法convertAndSend("MyQueue", "message");
Stream的使用
- 定义一个接口
public interface StreamClient{
String INPUT = "myMessage";
@Input(StreamClient.INPUT)
SubScribableChannel input();
@Output(StreamClient.INPUT)
MessageChannel output();
}
- stream接收
@EnableBingding(StreamClient.class)
public class Streamreceiver{
@StreamListener(StreamClient.INPUT)
public void process(Object message){
//do something
}
}
- stream发送
public class SendMessageController{
@Autowired
private StreamClient streamClient;
public void process(){
streamClient.output().send(MessageBuilder.withPayLoad("some message"));
}
}
Zuul
路由+过滤器 四个主要的过滤器
- pre filter
- routing filter
- post filter
- error filter
- 还有一个custom filter 自定义过滤器
限流
使用的算法:令牌桶 RateLimiter
redis StringRedisTemplate.opsForValue().set(XX)
鉴权
cookie/token
Hystrix
雪崩效应:多个服务调用,其中一个挂掉了,其他的服务请求不到,会不停地重试,占用了大量资源,导致也不可用,上级调用均不可用,导致一条链上的服务全部崩掉。
- 服务降级
1、启动类上加@EnableCircut
2、请求方法上加上@HystrixCommand(fallbackMethod = "方法名,如fallback")
3、写个降级后的处理,比如回调方法用fallback方法
public String fallback(){
return "网络太拥挤了,请稍后再试~";
}
- 超时设置
在@HystrixCommand上配置超时属性(名字太长,省略不记。。)
- 断路器
服务熔断:将正常的服务封装在断路器中,当服务出现一定概率的故障,就会触发断路机制
- feign hystrix
1、yml文件里加配置feign.hystrix.enabled=true
2、在@FeignClient注解上增加fallback参数,配置服务降级回调的类(类上要加注解@Component)
3、在启动类上增加包扫描
- hystrix dashboard hystrix的控制台
Sleuth+Zipkin 服务追踪
Sleuth链路追踪 zipkin控制台展示
1、引入zipkin和sleuth的依赖
2、yml中增加配置:spring.zipkin.baseUrl = http://localhost:9411
3、yml中增加配置:spring.sleuth.sampler.percentage=1(1代表100%,默认0.1/10%)