stream的引入是为了屏蔽底层消息中间件的差异,不过目前只支持rabbitmq和kafka两种和binding连接。
1.provider(生产消息)
1.1 导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2 编写yml文件(我这里连接rabbitmq发送消息)
server:
port: 8801
spring:
rabbitmq:
host: 192.168.43.158
port: 5672
username: test
password: test
virtual-host: /test
1.3 编写output输出接口
public interface MessageSend {
@Output("streamExchange")
MessageChannel output();
}
1.4 启动类中绑定输出接口
@SpringBootApplication
@EnableBinding(MessageSend.class)
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class,args);
}
}
1.5 编写controller层发送消息
@RestController
@RequestMapping("/provider")
public class MessageSendController {
@Resource
private MessageSend channel;
@GetMapping("/send")
public String messageSend(){
String s = UUID.randomUUID().toString();
channel.output().send(MessageBuilder.withPayload(s).build());
return "发送成功";
}
}
2.Constumer(消费者)
2.1 导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.2 编写yml文件
server:
port: 8802
spring:
rabbitmq:
host: 192.168.43.158
port: 5672
username: test
password: test
virtual-host: /test
2.3 编写接收接口
public interface ReceiveMessage {
@Input("streamExchange")
SubscribableChannel input();
}
2.4 编写启动类,绑定接受接口
@SpringBootApplication
@EnableBinding(ReceiveMessage.class)
public class consumerApplication {
public static void main(String[] args) {
SpringApplication.run(consumerApplication.class,args);
}
}
2.5 编写接受类,注入到spring
@Component
public class ReceiveMessageController {
@Value("${server.port}")
public String serverPort;
@StreamListener("streamExchange")
public void msg(Message<String> message){
System.out.println("接受的消息"+message.getPayload()+"port"+serverPort);
}
}
再建立一个一样的消费者
当消费者出现集群时,会进行消息的从夫消费,两个消费者都能接受到相同的消息进行消费,为了避免这种情况需要绑定消费者在同一个组中,当有消息的时候,会在组内进行竞争的方式进行消费
spring:
cloud:
stream:
bindings:
streamExchange:
group: consumer
进行分组后也能进行消息的持久化存储
在消费者当季的时候,生产者发送消息后,消息会在通道的组内进行持久化存储,当带有分组的消费者重启后依然能进行消息的消费