1. Dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
Define an interface:
package van.client.rabbit;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
/**
* @author Van
* @date 2020/4/11 - 11:53
*/
public interface RabbitClient {
@Input("MyMessage")
SubscribableChannel input();
@Output("MyMessage")
MessageChannel output();
}
3. Define a recipient
package van.client.rabbit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
/**
* @author Van
* @date 2020/4/11 - 11:55
*/
@Component
@EnableBinding(RabbitClient.class)
@Slf4j
public class StreamReceiver {
@StreamListener("MyMessage")
public void message(Object msg){
log.info("receive message:{}",msg);
}
}
4. Use the interface to send messages
package van.client.controller;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import van.client.rabbit.RabbitClient;
import javax.annotation.Resource;
/**
* @author Van
* @date 2020/4/11 - 12:01
*/
@RestController
@RequestMapping("/rabbit")
public class RabbitController {
@Resource
private RabbitClient rabbitClient;
@RequestMapping("/msg")
public void msg(){
String msg="rabbit message";
rabbitClient.output().send(MessageBuilder.withPayload(msg).build());
}
}
Start the project, visit localhost: 8080 / rabbit / msg and
you will see:
other:
1 **. In a cluster environment: **
When multiple projects are started, multiple queues named MyMessage will be created accordingly, and once a message is sent, all queues will receive messages, which of course is not the desired result. How to send a message once and only one item received?
Join in the configuration file: spring.cloud.stream.bindings.MyMessage.group = client
It is equivalent to all the clusters are grouped together, they share a queue named client.
When sending a message, only one item will be received.
2. If the sent msg is a java object, and I want to see the accumulated message in the queue.
Without any processing, what I see in the queue is a string that does not know what the ghost (encrypted with base64), so what should I do if I want to see a serialized java object?
Add in the configuration file:
spring.cloud.stream.bindings.MyMessage.content-type = application / json
Note that MyMessage is customized here, in fact, you can write anything.
If the receiver wants to send another message, it means that the message has been confirmed, you can add @SentTo ()
Advanced can see: this blog