SpringBoot配置RabbitMQ
配置maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件application.yml
spring:
rabbitmq:
username: user_mmr #用户名
password: 123 #密码
host: localhost # 你要连接的RabbitMQ的host
port: 5672 # Rabbit的port
virtual-host: '/vhost_mmr' #virtual-host
RabbitMQ教程
以下教程都可以在RabbitMQ在github的仓库rabbitmq-tutorial
中找到,具体springboot在spring-amqp
模块中。在这里面要讲一下如何运行相关代码
### 打包项目
mvn clean package
### 运行项目
java -jar xxx.jar --spring.profiles.active=tut1,sender
### 下面放上相关运行命令
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,receiver");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,sender");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=work-queues,receiver");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=work-queues,sender");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=pub-sub,receiver");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=pub-sub,sender");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=routing,receiver");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=routing,sender");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=topics,receiver");
System.out.println("java -jar rabbit-tutorials.jar --spring.profiles.active=topics,sender");
#### 注意,该项目使用了定时任务
你需要配置允许定时调度的注解
@EnableScheduling
helloworld
@Profile({"tut1","hello-world"})
@Configuration
public class Tut1Config {
@Bean
public Queue hello(){
return new Queue("hello");
}
@Profile("receiver")
@Bean
public Tut1Receiver receiver(){
return new Tut1Receiver();
}
@Profile("sender")
@Bean
public Tut1Sender sender(){
return new Tut1Sender();
}
}
// 监听hello队列 Annotation that marks a method to be the target of a Rabbit message listener on the
// specified queues()或者bindings().
@RabbitListener(queues = "hello")
public class Tut1Receiver {
private static final Logger logger = LoggerFactory.getLogger(Tut1Receiver.class);
// Annotation that marks a method to be the target of a Rabbit message
// listener within a class that is annotated with {@link RabbitListener}
@RabbitHandler
public void receive(String in) {
logger.info("[x] Received:{} ", in);
System.out.println("[x] Received:{} "+ in);
}
}
public class Tut1Sender {
private final static Logger logger = LoggerFactory.getLogger(Tut1Sender.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private Queue queue;
@Scheduled(fixedDelay = 1000, initialDelay = 500)
public void send() {
String msg = "hello world";
this.rabbitTemplate.convertAndSend(queue.getName(), msg);
logger.info("[x] sent :" + msg);
System.out.println("[x] sent :" + msg);
}
}
// java -jar xxx.jar --spring.profiles.active=hello-world,receiver
// java -jar xxx.jar --spring.profiles.active=hello-world,sender
work-queues
@RabbitListener(queues = "tut.hello")
public class Tut2Receiver {
private final static Logger logger = LoggerFactory.getLogger(Tut2Receiver.class);
private final int instance;
public Tut2Receiver(int i){
this.instance = i;
}
@RabbitHandler
public void receive(String in) throws InterruptedException{
StopWatch watch = new StopWatch();
watch.start();
logger.info("instance " + this.instance+"[x] recived" + in);
doWork(in);
watch.stop();
logger.info("instance " + this.instance +"[x] done");
}
private void doWork(String in) throws InterruptedException{
for (char ch:in.toCharArray()){
if(ch == '.'){
TimeUnit.SECONDS.sleep(1);
}
}
}
}
public class Tut2Sender {
private static Logger logger = LoggerFactory.getLogger(Tut2Sender.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private Queue queue;
AtomicInteger dots = new AtomicInteger(0);
AtomicInteger count = new AtomicInteger(0);
@Scheduled(fixedDelay = 1000,initialDelay = 500)
public void send(){
StringBuilder builder = new StringBuilder("hello");
if(dots.getAndIncrement() == 3){
dots.set(1);
}
for(int i = 0;i<dots.get();i++){
builder.append(".");
}
builder.append(count.incrementAndGet());
String msg = builder.toString();
rabbitTemplate.convertAndSend(queue.getName(),msg);
logger.info("[x] sent {}",msg);
}
}
@Profile({"tut2","work-queues"})
@Configuration
public class Tut2Config {
@Bean
public Queue hello(){
return new Queue("tut.hello");
}
@Profile("receiver")
private static class ReceiverConfig{
@Bean
public Tut2Receiver receiver1(){
return new Tut2Receiver(1);
}
@Bean
public Tut2Receiver receiver2(){
return new Tut2Receiver(2);
}
}
@Profile("sender")
@Bean
public Tut2Sender sender(){
return new Tut2Sender();
}
}
pub-sub
@Configuration
@Profile({"tut3","pub-sub","publish-subscribe"})
public class Tut3Config {
@Bean
public FanoutExchange fanout(){
return new FanoutExchange("tut.fanout");
}
@Profile("receiver")
private static class ReceiverConfig{
@Bean
public Queue autoDeleteQueue1(){
return new AnonymousQueue();
}
@Bean
public Queue autoDeleteQueue2(){
return new AnonymousQueue();
}
// 这个地方可能注册不成功
@Bean
public Binding binding1(FanoutExchange fanout,Queue autoDeleteQueue1){
return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
}
@Bean
public Binding binding2(FanoutExchange fanout,Queue autoDeleteQueue2){
return BindingBuilder.bind(autoDeleteQueue2).to(fanout);
}
@Bean
public Tut3Receiver receiver(){
return new Tut3Receiver();
}
}
@Profile("sender")
@Bean
public Tut3Sender sender(){
return new Tut3Sender();
}
}
public class Tut3Receiver {
@RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in) throws InterruptedException{
receive(in,1);
}
@RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in) throws InterruptedException{
receive(in,2);
}
public void receive(String in,int receiver) throws InterruptedException{
StopWatch watch = new StopWatch();
watch.start();
System.out.println("instance " + receiver + "[x] Received" + in);
doWork(in);
watch.stop();
System.out.println("instance" + receiver + "[x] Done in" + watch.getTotalTimeSeconds()+"s");
}
private void doWork(String in) throws InterruptedException{
for(char ch: in.toCharArray()){
if(ch == '.'){
TimeUnit.SECONDS.sleep(1);
}
}
}
}
public class Tut3Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private FanoutExchange fanout;
AtomicInteger dots = new AtomicInteger(0);
AtomicInteger count = new AtomicInteger(0);
@Scheduled(fixedDelay = 1000,initialDelay = 500)
public void send(){
StringBuilder builder = new StringBuilder("hello");
if(dots.getAndIncrement() == 3){
dots.set(1);
}
for(int i = 0;i < dots.get();i++){
builder.append(".");
}
builder.append(count.incrementAndGet());
String message = builder.toString();
rabbitTemplate.convertAndSend(fanout.getName(),"",message);
System.out.println("[x] sent" +message);
}
}
direct
@Profile({"tut4","routing"})
@Configuration
public class Tut4Config {
// 设置exchange
@Bean
public DirectExchange direct(){
return new DirectExchange("tut.direct");
}
@Profile("receiver")
private static class ReceiverConfig{
// 创建两个匿名Queue an anonymous, non-durable, exclusive, auto-delete queue
@Bean
public Queue autoDeleteQueue1(){
return new AnonymousQueue();
}
@Bean
public Queue autoDeleteQueue2(){
return new AnonymousQueue();
}
// 绑定相关数据
@Bean
public Binding binding1a(DirectExchange directExchange,Queue autoDeleteQueue1){
return BindingBuilder.bind(autoDeleteQueue1).to(directExchange).with("orange");
}
@Bean
public Binding binding1b(DirectExchange directExchange,Queue autoDeleteQueue1){
return BindingBuilder.bind(autoDeleteQueue1).to(directExchange).with("black");
}
@Bean
public Binding binding2a(DirectExchange directExchange,Queue autoDeleteQueue2){
return BindingBuilder.bind(autoDeleteQueue2).to(directExchange).with("green");
}
@Bean
public Binding binding2b(DirectExchange direct,Queue autoDeleteQueue2){
return BindingBuilder.bind(autoDeleteQueue2).to(direct).with("black");
}
//
@Bean
public Tut4Receiver receiver(){
return new Tut4Receiver();
}
}
@Profile("sender")
@Bean
public Tut4Sender sender(){
return new Tut4Sender();
}
}
public class Tut4Receiver {
@RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in) throws InterruptedException{
receive(in,1);
}
@RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in) throws InterruptedException{
receive(in,2);
}
public void receive(String in,int receiver) throws InterruptedException{
StopWatch watch = new StopWatch();
watch.start();
System.out.println("instance " + receiver+"[x] received ' " + in+ "'");
doWork(in);
watch.stop();
System.out.println("instance "+ receiver+"[x] Done in" + watch.getTotalTimeSeconds()+"s");
}
private void doWork(String in) throws InterruptedException{
for(char ch: in.toCharArray()){
if(ch == '.'){
TimeUnit.SECONDS.sleep(1);
}
}
}
}
public class Tut4Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private DirectExchange directExchange;
AtomicInteger index = new AtomicInteger(0);
AtomicInteger count = new AtomicInteger(0);
private final String[] keys = {"orange", "black", "green"};
@Scheduled(fixedDelay = 1000, initialDelay = 500)
public void send() {
StringBuilder builder = new StringBuilder("Hello to ");
if (this.index.incrementAndGet() == 3) {
this.index.set(0);
}
String key = keys[this.index.get()];
builder.append(key).append(' ');
builder.append(this.count.incrementAndGet());
String message = builder.toString();
rabbitTemplate.convertAndSend(directExchange.getName(), key, message);
System.out.println("[X] sent '" + message + "'");
}
}
topic
@Profile({"tut5","topics"})
@Configuration
public class Tut5Config {
@Bean
public TopicExchange topicExchange(){
return new TopicExchange("tut.topic");
}
@Profile("receiver")
private static class ReceiverConfig{
@Bean
public Tut5Receiver receiver(){
return new Tut5Receiver();
}
@Bean
public Queue autoDeleteQueue1(){
return new AnonymousQueue();
}
@Bean
public Queue autoDeleteQueue2(){
return new AnonymousQueue();
}
@Bean
public Binding binding1a(TopicExchange topicExchange,Queue autoDeleteQueue1){
return BindingBuilder.bind(autoDeleteQueue1).to(topicExchange).with("*.orange.*");
}
@Bean
public Binding binding1b(TopicExchange topicExchange,Queue autoDeleteQueue1){
return BindingBuilder.bind(autoDeleteQueue1).to(topicExchange).with("*.*.rabbit");
}
@Bean
public Binding binding2a(TopicExchange topic,Queue autoDeleteQueue2){
return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("lazy.#");
}
}
@Profile("sender")
@Bean
public Tut5Sender sender(){
return new Tut5Sender();
}
}
public class Tut5Receiver {
@RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in) throws InterruptedException {
receive(in, 1);
}
@RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in) throws InterruptedException {
receive(in, 2);
}
public void receive(String in, int receiver) throws InterruptedException {
StopWatch watch = new StopWatch();
watch.start();
System.out.println("instance " + receiver + " [X] received ' " + in + " '");
doWork(in);
watch.stop();
System.out.println("instance " + receiver + " [X] Done in" + watch.getTotalTimeSeconds() +"s");
}
private void doWork(String in) throws InterruptedException{
for(char ch : in.toCharArray()){
if(ch == '.'){
TimeUnit.SECONDS.sleep(1);
}
}
}
}
public class Tut5Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private TopicExchange topicExchange;
AtomicInteger index = new AtomicInteger(0);
AtomicInteger count = new AtomicInteger(0);
private final String[] keys = {"quick.orange.rabbit", "lazy.orange.elephant", "quick.orange.fox",
"lazy.brown.fox", "lazy.pink.rabbit", "quick.brown.fox"};
@Scheduled(fixedDelay = 1000,initialDelay = 500)
public void send(){
StringBuilder builder = new StringBuilder("Hello to ");
if(this.index.incrementAndGet() == keys.length){
this.index.set(0);
}
String key = keys[this.index.get()];
builder.append(key).append(" ");
builder.append(this.count.incrementAndGet());
String message = builder.toString();
rabbitTemplate.convertAndSend(topicExchange.getName(),key,message);
}
}