1.导入依赖
<!--rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.application.yml
server:
port: 8090
test:
rabbitmq:
host: 172.xx.xx.xx
port: 5672
username: root
password: root
3.从application中获取配置内容
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "test.rabbitmq")
public class RabbitMqConfig{
private String host;
private int port;
private String username;
private String password;
}
4.RabbitMQ的工厂类
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class ConnectionMqConfig {
@Autowired
private RabbitMqConfig rabbitMqConfig;
@Bean
public CachingConnectionFactory connectionFactory() throws Exception {
//创建工厂类
CachingConnectionFactory cachingConnectionFactory=new CachingConnectionFactory();
//用户名
cachingConnectionFactory.setUsername(rabbitMqConfig.getUsername());
//密码
cachingConnectionFactory.setPassword(rabbitMqConfig.getPassword());
//rabbitMQ地址
cachingConnectionFactory.setHost(rabbitMqConfig.getHost());
//rabbitMQ端口
cachingConnectionFactory.setPort(rabbitMqConfig.getPort());
cachingConnectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CHANNEL);
return cachingConnectionFactory;
}
/**
* 将配置好的信息放入
* @param connectionFactory
* @return
*/
@Bean
public RabbitListenerContainerFactory rabbitListenerContainerFactory(CachingConnectionFactory connectionFactory){
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory( connectionFactory);
return factory;
}
/**
* 自动声明队列
* @param connectionFactory
* @return
*/
@Bean
public RabbitAdmin rabbitAdmin(CachingConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
}
5.监听类
@Slf4j
@Component
public class TopicManReceiver {
@Autowired
private RabbitMqConfig rabbitMqConfig;
@RabbitListener(queues = "队列名称")
public void processReport(byte[] testMessage) {
try {
String strContent = new String(testMessage, "utf-8");
System.out.println("TopicManReceiver消费者收到消息 : " + strContent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
参考文章:https://www.cnblogs.com/daijiting/p/11527517.html