springboot2.1以javabean整合rabbitmq及自动注入rabbitmqTemplate为空问题
springboot集成rabbitmq之前也写过,这次再来个总结,总体来讲比较简单
主要就是配置属性文件,将属性以javabean的形式注入,配置工厂,对象等原来以xml<bean>形式注入的对象。
代码如下properties属性
#rabbitMQ配置
rabbit.config.host=192.168.135.129
rabbit.config.port=5672
rabbit.config.userName=guest
rabbit.config.password=guest
/**
*
*/
package com.sharp.forward.config; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; /**
* @author 醉逍遥
*
*/
@Component
@ConfigurationProperties(prefix="rabbit.config")
@PropertySource(value="classpath:config/rabbitmq.properties",encoding="utf-8")
public class RabbitMQProperties { public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} private String host; private int port; private String userName; private String password; }
/**
*
*/
package com.sharp.forward.config; import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.ConsumerTagStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; /**
* @author 醉逍遥
*
*/
@Configuration
public class RabbitMQConf{ @Autowired
private RabbitMQProperties rabbitMQProperties; // 获取连接工厂
@Bean
public ConnectionFactory factory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setHost(rabbitMQProperties.getHost());
factory.setPort(rabbitMQProperties.getPort());
factory.setUsername(rabbitMQProperties.getUserName());
factory.setPassword(rabbitMQProperties.getPassword());
return factory;
}
// 获取rabbitmqAdmin
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
RabbitAdmin admin = new RabbitAdmin(factory);
admin.setAutoStartup(true);
return admin;
} @Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
RabbitTemplate template =new RabbitTemplate(factory);
return template;
} /**
* 不配置这个容器,启动项目时候,rabbitmq的管控台看不到动作
* @param factory
* @return
*/
@Bean
public SimpleMessageListenerContainer container(ConnectionFactory factory) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(factory);
container.setConsumerTagStrategy(new ConsumerTagStrategy() { @Override
public String createConsumerTag(String queue) {
return null;
}
});
return container;
} // 定义交换器
public static final String SHARP_EXANGE_TEST_001="sharpExchangeTest001"; public static final String SHARP_EXANGE_TEST_002="sharpExchangeTest002"; public static final String SHARP_EXANGE_TEST_003="sharpExchangeTest003";
// 定义队列
public static final String SHARP_QUEUE_TEST_001="sharpQueueTest001"; public static final String SHARP_QUEUE_TEST_002="sharpQueueTest002"; public static final String SHARP_QUEUE_TEST_003="sharpQueueTest003";
// 定义路由键
public static final String SHARP_ROUTINGKEY_TEST_001="sharp.test"; public static final String SHARP_ROUTINGKEY_TEST_002="sharp.topic.#"; @Bean(name="sharpExchangeTest001")
public DirectExchange getExchage_001() {
return new DirectExchange(SHARP_EXANGE_TEST_001, true, false, null);
}
@Bean(name="sharpExchangeTest002")
public TopicExchange getExchange_002() {
return new TopicExchange(SHARP_EXANGE_TEST_002, true, false, null);
}
@Bean(name="sharpExchangeTest003")
public FanoutExchange getExchange_003() {
return new FanoutExchange(SHARP_EXANGE_TEST_003, true, false, null);
}
@Bean(name="sharpQueueTest001")
public Queue getQueue_001() {
return new Queue(SHARP_QUEUE_TEST_001, true, false, false, null);
}
@Bean(name="sharpQueueTest002")
public Queue getQueue_002() {
return new Queue(SHARP_QUEUE_TEST_002, true, false, false, null);
}
@Bean(name="sharpQueueTest003")
public Queue getQueue_003() {
return new Queue(SHARP_QUEUE_TEST_003, true, false, false, null);
}
// 定义绑定
@Bean
public Binding getDirectBinding() {
return BindingBuilder.bind(getQueue_001()).to(getExchage_001()).with(SHARP_ROUTINGKEY_TEST_001);
} @Bean
public Binding getTopicBinding() {
return BindingBuilder.bind(getQueue_002()).to(getExchange_002()).with(SHARP_ROUTINGKEY_TEST_002);
} @Bean
public Binding getFauoutBinding() {
return BindingBuilder.bind(getQueue_003()).to(getExchange_003());
}
}
rabbitUtil
/**
*
*/
package com.sharp.forward.util; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import com.sharp.forward.config.RabbitMQConf; /**
* @author 醉逍遥
*/
@Component
public class RabbitUtil { private static final Logger logger = LoggerFactory.getLogger(RabbitUtil.class); @Autowired
private RabbitTemplate template; public void sendObjectMessage(Object obj) {
template.convertAndSend("sharpExchangeTest001", "sharp.test", obj);
} public void sendStringMessage(String message) { } public void sendMessage(String message) {
logger.info("rabbitUtil发送消息前的信息:{}",message);
logger.info("template是否为空:{}",(template==null));
template.convertAndSend(RabbitMQConf.SHARP_EXANGE_TEST_001, RabbitMQConf.SHARP_ROUTINGKEY_TEST_001, message==null?"hello":message);
}
}
rabbitServiceImpl(service代码就不贴了)
/**
*
*/
package com.sharp.forward.user.serviceImpl; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.sharp.forward.user.service.RabbitService;
import com.sharp.forward.util.RabbitUtil; /**
* @author 醉逍遥
*
*/
@Service("rabbitService")
@Transactional(readOnly=true)
public class RabbitServiceImpl implements RabbitService{ private static final Logger logger = LoggerFactory.getLogger(RabbitServiceImpl.class);
@Autowired
private RabbitUtil util;
@Override
public void sendObjectMessage(String message) {
logger.info("要发送的参数是:------> {}",message);
util.sendMessage(message);
}
}
之前运行一直在rabbitUtil中报rabbitTemplate注入始终为空,导致消息不能发送,是因为我之前在service层25行处用的RabbitUtil不是用的@Autowired注入,而是用了new RabbitUtil,尽管RabbitUtil中用的@Autowired注入了模板,找错时一直在rabbitUtil中找找不到错误,后来将RabbitUtil注解为@Companent,service层对应修改为spring注入,Ok
启动项
package com.sharp.forward; import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import com.sharp.forward.config.RabbitMQProperties; @SpringBootApplication
//@ImportResource("classpath:config/application-user-service-dubbo.xml")
@MapperScan(basePackages= {"com.sharp.forward.mapper"})
@EnableAutoConfiguration
public class Application implements CommandLineRunner{ private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} @Autowired
private RabbitMQProperties rabbitMQProperties; /**
* @param args
* @throws Exception
*/
@Override
public void run(String... args) throws Exception {
String config = "host: " + rabbitMQProperties.getHost()
+ ", config.port:" + rabbitMQProperties.getPort()
+ ", config.userName:" + rabbitMQProperties.getUserName(); log.info("SpringBoot2.0实现自定义properties配置文件与JavaBean映射: {}" , config); } }
然后在消费服务中测试
代码如下
@PostMapping("/sendString")
public void sendString(@Param(value = "message") String message) {
logger.info("start send message test: {}",message);
rabbitService.sendObjectMessage(message);
}
测试后在管控台看到消息
主要结构
springboot2.1以javabean整合rabbitmq及自动注入rabbitmqTemplate为空问题的更多相关文章
- Spring与Struts2整合时action自动注入的问题
当Struts和Spring框架进行整合时,原本由action实例化对象的过程移交给spring来做(这个过程依赖一个叫struts2-spring-plugin的jar包,这个包主要的功能就是实现刚 ...
- SpringBoot2.0源码分析(三):整合RabbitMQ分析
SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ RabbitMQ自动注入 当项目中存在org.springfr ...
- SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ
如何整合RabbitMQ 1.添加spring-boot-starter-amqp <dependency> <groupId>org.springframework.boot ...
- java框架之SpringBoot(12)-消息及整合RabbitMQ
前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...
- spring boot实战(第十二篇)整合RabbitMQ
前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...
- Spring Boot 整合 rabbitmq
一.消息中间件的应用场景 异步处理 场景:用户注册,信息写入数据库后,需要给用户发送注册成功的邮件,再发送注册成功的邮件. 1.同步调用:注册成功后,顺序执行发送邮件方法,发送短信方法,最后响应用户 ...
- springboot 学习之路 20 (整合RabbitMQ)
整合RabbitMQ: 我的操作系统是window7 ,所以在整合ribbotMQ之前需要先安装rabbitMq服务:安装步骤请参考:window下安装RabbitMQ 这个详细介绍了安装步骤,请按 ...
- Spring Boot整合RabbitMQ详细教程
原文:https://blog.csdn.net/qq_38455201/article/details/80308771 1.首先我们简单了解一下消息中间件的应用场景 异步处理 场景说明:用户注册后 ...
- springboot整合rabbitmq,支持消息确认机制
安装 推荐一篇博客https://blog.csdn.net/zhuzhezhuzhe1/article/details/80464291 项目结构 POM.XML <?xml version= ...
随机推荐
- python字典操作方法详解
前言 字典是一种通过名字或者关键字引用的得数据结构,key 类型需要时被哈希,其键可以是数字.字符串.元组,这种结构类型也称之为映射.字典类型是Python中唯一內建的映射类型. 注意,浮点数比较很不 ...
- 解决方法:Could not load file or assembly 'WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
最近使用VS2015调试ASP.NET 程序遇到了该问题: 在网上找了很多方法都不能解决,最后自己解决了,方法如下: 在project -> NuGet管理中找到已安装的所有程序:将Web Op ...
- ubuntu-18.04 修改用户名密码
1. 开放root登录 设置root密码 $ sudo passwd root 切换到root 用户 $ sudo -i 修改/etc/pam.d/gdm-autologin $ vim /etc/p ...
- 阿里云linux挂载磁盘
1)使用fdisk -l命令查看主机上的硬盘 2.使用mkfs.ext4命令把硬盘格式化: mkfs.ext4 磁盘名称 如:mkfs.ext4 /dev/vdb/ 3. 使用mount命令 ...
- Java基础知识笔记第七章:内部类和异常类
内部类 /* *Java支持在一个类中定义另一个类,这样的类称为内部类,而包含内部类的类称为内部类的外嵌类 */ 重要关系: /* *1.内部类的外嵌类在内部类中仍然有效,内部类的方法也可以外嵌类的方 ...
- 4 CSS导航栏&下拉菜单&属性选择器&属性和值选择器
CSS导航栏 熟练使用导航栏,对于任何网站都非常重要 使用CSS你可以转换成好看的导航栏而不是枯燥的HTML菜单 垂直导航栏: <!DOCTYPE html> <html> & ...
- 吴裕雄--天生自然ORACLE数据库学习笔记:用户管理与权限分配
create user mr identified by mrsoft default tablespace users temporary tablespace temp; create user ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 表格:为任意 <table> 添加基本样式 (只有横向分隔线)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 使用阿里云服务器配置frp实现Windows系统RDP内网穿透
1.frp服务器采用阿里云ecs的centos7.5系统,客户端是台windows10的系统,做一个RDP服务的内网穿透用. 2.首先下载frp到服务器(链接:https://github.com/f ...
- LeetCode 345. Reverse Vowels of a String(双指针)
题意:给定一个字符串,反转字符串中的元音字母. 例如: Input: "leetcode" Output: "leotcede" 法一:双指针 class So ...