Spring Cloud Bus可以将分布式系统的节点与轻量级消息代理链接,然后可以实现广播状态更改(例如配置更改)或广播其他管理指令。

需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求 :二一四七七七五六三三
生产者:
创建消息,然后发布到代理服务器(RabbitMQ)

消费者:
连接到代理服务器(RabbitMQ)上,并订阅到队列上。不会知道谁是消息的生产者

整个过程:

生产者创建消息,消费者接收消息。

消息:包括有效载荷与标签

有效载荷:要传输的数据

标签:描述有效载荷,并且RabbitMQ使用标签决定谁将获得消息的拷贝;

信道:
生产者和消费者与代理服务器之间的通信必须建立一个信道。

Spring Cloud Bus就像一个分布式执行器,用于扩展的Spring Boot应用程序,但也可以用作应用程序之间的通信通道。那么这里就涉及到了消息代理,目前流行的消息代理中间件有不少,Spring Cloud Bus支持RabbitMQ和Kafka,本文我们主要来看看RabbitMQ的基本使用。

首先你需要安装RabbitMQ,打开浏览器登录 http://localhost:15672,打开web管理界面,默认账号和密码都是guest。新建自己的用户名,并给予权限,然后创建队列的名称,下面配置文件有注释。

Maven

      <!--rabbitmq消息-->
        <dependency>
            <groupId>org.spring work.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

配置文件

rabbitmq 集成 gaomin要在http://localhost:15672/#/users 添加 同时代码里面用的helloQueue 队列名称也要在 http://localhost:15672/#/queues 添加。

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=gaomin
spring.rabbitmq.password=123456
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.virtual-host=/

提供者

/**
 * 需要到后台添加队列Name helloQueue
 * Created by gaomin on 2017/12/4.
 */
@Component
public class HelloSender {
    @Autowired
    private AmqpTemplate rabbitTemplate;
 
    public void send() {
        String sendMsg = \"hello1 \" + new Date();
        System.out.println(\"Sender1 : \" + sendMsg);
        this.rabbitTemplate.convertAndSend(\"helloQueue\", sendMsg);
    }
}

消费者

/**
 * Created by gaomin on 2017/12/28.
 */
@Component
@RabbitListener(queues = \"helloQueue\")
public class HelloReceiver {
    @RabbitHandler
    public void process(String hello) {
        System.out.println(\"Receiver1  : \" + hello);
    }
}

测试一波

@RestController
@RequestMapping(value = \"rabbit\")
public class RabbitTest {
    @Autowired
    private HelloSender helloSender;
 
    @RequestMapping(\"/test\")
    public String test() {
        helloSender.send();
        return \"发送成功\";
    }
}

你会发现当你请求这个接口时会发送一条消息,HelloReceiver会接受到send的消息。

springboot微服务多用户商城系统java_代码开源_B2B电商系统_B2C电商系统

收藏 打印