您的位置:首页 > 编程语言 > Java开发

Spring Cloud Bus 消息总线

2018-03-19 17:08 561 查看

Spring Cloud Bus 消息总线

安装RabbitMQ

下载并安装Erlang和RabbitMQ

rabbitmq自带管理后台,安装后需要配置开启

进入rabbitmq安装目录中的sbin目录执行

rabbitmq-plugins enable rabbitmq_management

重启rabbitmq服务生效

打开http://localhost:15672/即可看到管理后台

用户名密码均为guest 【此用户只能本地使用】

测试RabbitMQ栗子:

创建新的RabbitMQ用户 【springcloud,123456】

创建项目:rabbitmq-hello

依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


配置:

spring.application.name=rabbitmq-hello
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=springcloud
spring.rabbitmq.password=123456


配置类:

@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue(){
return  new Queue("hello");
}
}


消息生产类:

@Component
public class Sender {
/*消息生产者*/
@Autowired
private AmqpTemplate rabbitTemplate;

public void send(){
String context = "hello " + new Date();
System.out.println("Sender:"+context);
this.rabbitTemplate.convertAndSend("hello",context);
}
}


消息消费类:

@Component
@RabbitListener(queues = "hello")
public class Receiver {
/*消息消费者*/
@RabbitHandler
public void process(String hello){
System.out.println("Receiver:"+hello);
}
}


测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RabbitmqHelloApplication.class)
public class RabbitmqHelloApplicationTests {
@Autowired
public Sender sender;

@Test
public void hello() throws Exception {
sender.send();
}
}


测试

确定RabbitMQ服务开启

启动应用主类【可以发现在RabbitMQ控制页面发现多了东东】

启动测试类进行测试【消息消费类会被执行,打印出信息】

完成栗子

整合Bus【整合到整个Cloud里面】

整合到一起,目前所知的只是用来做Config组件配置信息的自动刷新

在config-server,config-client,Eureka 添加依赖与配置

依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>


配置:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=springcloud
spring.rabbitmq.password=123456


完成咯。。。。。【对,就是这么简单。。】

测试

启动所有项目

访问配置【git-config-dev-5.0】

修改Git配置【git-config-dev-6.0】

使用任意端点刷新【localhost:7002/bus/refresh】

访问所有服务【config-client:7002/7003】,配置都更新为最新【git-config-dev-6.0】

这个还有局部刷新的参数:/bus/refresh?destination=customers:9000

感觉没什么球用 ╮(╯_╰)╭

遇到的问题:

RabbitMQ新创建的用户,在使用前要求去授权页面点点,然后重启!

这里的自动刷新,还是必须手动发送一个/bus/refresh 才行 (ノ`Д)ノ

如果使用/refresh 的话,依旧只是更新单个服务

参考:

https://www.linuxidc.com/Linux/2014-10/107917.htm

http://www.60kb.com/post/87.html

小杭 20180319
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息