pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springrmqsender</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
</project>
配置文件:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
MyRabbitConfig
package org.example.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRabbitConfig
{
public final static String FANOUT_NAME ="amqp-fanout";
@Bean
FanoutExchange fanoutExchange(){
return new FanoutExchange(FANOUT_NAME,true,false);
}
}
发送消息:
package org.example.sender;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 消息生产者 发送消息
*/
@Component
public class MessageSender {
@Autowired
RabbitTemplate rabbitTemplate;
/**
* 发送消息
* @param info
*/
public void send(String info)
{
System.out.println("发送消息>>>"+info);
rabbitTemplate.convertAndSend("amqp-fanout","",info);
}
}
通过服务发送:
package org.example.controller;
import org.example.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther: moerhai@qq.com
* @Date: 2020/10/4 11:34
*/
@RestController
public class IndexController {
@Autowired
MessageSender messageSender;
@RequestMapping("/index")
public String index()
{
messageSender.send("中国——生产者");
return "SUCCESS";
}
}
所有评论(0)