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
1 /** 2 * 3 */ 4 package com.sharp.forward.config; 5 6 import org.springframework.boot.context.properties.ConfigurationProperties; 7 import org.springframework.context.annotation.PropertySource; 8 import org.springframework.stereotype.Component; 9 10 /** 11 * @author 醉逍遥 12 * 13 */ 14 @Component 15 @ConfigurationProperties(prefix="rabbit.config") 16 @PropertySource(value="classpath:config/rabbitmq.properties",encoding="utf-8") 17 public class RabbitMQProperties { 18 19 public String getHost() { 20 return host; 21 } 22 23 public void setHost(String host) { 24 this.host = host; 25 } 26 27 public int getPort() { 28 return port; 29 } 30 31 public void setPort(int port) { 32 this.port = port; 33 } 34 35 public String getUserName() { 36 return userName; 37 } 38 39 public void setUserName(String userName) { 40 this.userName = userName; 41 } 42 43 public String getPassword() { 44 return password; 45 } 46 47 public void setPassword(String password) { 48 this.password = password; 49 } 50 51 private String host; 52 53 private int port; 54 55 private String userName; 56 57 private String password; 58 59 60 61 }
1 /** 2 * 3 */ 4 package com.sharp.forward.config; 5 6 import org.springframework.amqp.core.Binding; 7 import org.springframework.amqp.core.BindingBuilder; 8 import org.springframework.amqp.core.DirectExchange; 9 import org.springframework.amqp.core.FanoutExchange; 10 import org.springframework.amqp.core.Queue; 11 import org.springframework.amqp.core.TopicExchange; 12 import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; 13 import org.springframework.amqp.rabbit.connection.ConnectionFactory; 14 import org.springframework.amqp.rabbit.core.RabbitAdmin; 15 import org.springframework.amqp.rabbit.core.RabbitTemplate; 16 import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; 17 import org.springframework.amqp.support.ConsumerTagStrategy; 18 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.context.annotation.Bean; 20 import org.springframework.context.annotation.ComponentScan; 21 import org.springframework.context.annotation.Configuration; 22 import org.springframework.stereotype.Component; 23 24 /** 25 * @author 醉逍遥 26 * 27 */ 28 @Configuration 29 public class RabbitMQConf{ 30 31 @Autowired 32 private RabbitMQProperties rabbitMQProperties; 33 34 // 获取连接工厂 35 @Bean 36 public ConnectionFactory factory() { 37 CachingConnectionFactory factory = new CachingConnectionFactory(); 38 factory.setHost(rabbitMQProperties.getHost()); 39 factory.setPort(rabbitMQProperties.getPort()); 40 factory.setUsername(rabbitMQProperties.getUserName()); 41 factory.setPassword(rabbitMQProperties.getPassword()); 42 return factory; 43 } 44 // 获取rabbitmqAdmin 45 @Bean 46 public RabbitAdmin rabbitAdmin(ConnectionFactory factory) { 47 RabbitAdmin admin = new RabbitAdmin(factory); 48 admin.setAutoStartup(true); 49 return admin; 50 } 51 52 @Bean 53 public RabbitTemplate rabbitTemplate(ConnectionFactory factory) { 54 RabbitTemplate template =new RabbitTemplate(factory); 55 return template; 56 } 57 58 /** 59 * 不配置这个容器,启动项目时候,rabbitmq的管控台看不到动作 60 * @param factory 61 * @return 62 */ 63 @Bean 64 public SimpleMessageListenerContainer container(ConnectionFactory factory) { 65 SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(factory); 66 container.setConsumerTagStrategy(new ConsumerTagStrategy() { 67 68 @Override 69 public String createConsumerTag(String queue) { 70 return null; 71 } 72 }); 73 return container; 74 } 75 76 // 定义交换器 77 public static final String SHARP_EXANGE_TEST_001="sharpExchangeTest001"; 78 79 public static final String SHARP_EXANGE_TEST_002="sharpExchangeTest002"; 80 81 public static final String SHARP_EXANGE_TEST_003="sharpExchangeTest003"; 82 // 定义队列 83 public static final String SHARP_QUEUE_TEST_001="sharpQueueTest001"; 84 85 public static final String SHARP_QUEUE_TEST_002="sharpQueueTest002"; 86 87 public static final String SHARP_QUEUE_TEST_003="sharpQueueTest003"; 88 // 定义路由键 89 public static final String SHARP_ROUTINGKEY_TEST_001="sharp.test"; 90 91 public static final String SHARP_ROUTINGKEY_TEST_002="sharp.topic.#"; 92 93 @Bean(name="sharpExchangeTest001") 94 public DirectExchange getExchage_001() { 95 return new DirectExchange(SHARP_EXANGE_TEST_001, true, false, null); 96 } 97 @Bean(name="sharpExchangeTest002") 98 public TopicExchange getExchange_002() { 99 return new TopicExchange(SHARP_EXANGE_TEST_002, true, false, null); 100 } 101 @Bean(name="sharpExchangeTest003") 102 public FanoutExchange getExchange_003() { 103 return new FanoutExchange(SHARP_EXANGE_TEST_003, true, false, null); 104 } 105 @Bean(name="sharpQueueTest001") 106 public Queue getQueue_001() { 107 return new Queue(SHARP_QUEUE_TEST_001, true, false, false, null); 108 } 109 @Bean(name="sharpQueueTest002") 110 public Queue getQueue_002() { 111 return new Queue(SHARP_QUEUE_TEST_002, true, false, false, null); 112 } 113 @Bean(name="sharpQueueTest003") 114 public Queue getQueue_003() { 115 return new Queue(SHARP_QUEUE_TEST_003, true, false, false, null); 116 } 117 // 定义绑定 118 @Bean 119 public Binding getDirectBinding() { 120 return BindingBuilder.bind(getQueue_001()).to(getExchage_001()).with(SHARP_ROUTINGKEY_TEST_001); 121 } 122 123 @Bean 124 public Binding getTopicBinding() { 125 return BindingBuilder.bind(getQueue_002()).to(getExchange_002()).with(SHARP_ROUTINGKEY_TEST_002); 126 } 127 128 @Bean 129 public Binding getFauoutBinding() { 130 return BindingBuilder.bind(getQueue_003()).to(getExchange_003()); 131 } 132 }
rabbitUtil
1 /** 2 * 3 */ 4 package com.sharp.forward.util; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.amqp.rabbit.core.RabbitTemplate; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.stereotype.Component; 11 12 import com.sharp.forward.config.RabbitMQConf; 13 14 /** 15 * @author 醉逍遥 16 */ 17 @Component 18 public class RabbitUtil { 19 20 private static final Logger logger = LoggerFactory.getLogger(RabbitUtil.class); 21 22 @Autowired 23 private RabbitTemplate template; 24 25 public void sendObjectMessage(Object obj) { 26 template.convertAndSend("sharpExchangeTest001", "sharp.test", obj); 27 } 28 29 public void sendStringMessage(String message) { 30 31 } 32 33 public void sendMessage(String message) { 34 logger.info("rabbitUtil发送消息前的信息:{}",message); 35 logger.info("template是否为空:{}",(template==null)); 36 template.convertAndSend(RabbitMQConf.SHARP_EXANGE_TEST_001, RabbitMQConf.SHARP_ROUTINGKEY_TEST_001, message==null?"hello":message); 37 } 38 }
rabbitServiceImpl(service代码就不贴了)
1 /** 2 * 3 */ 4 package com.sharp.forward.user.serviceImpl; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Service; 10 import org.springframework.transaction.annotation.Transactional; 11 12 import com.sharp.forward.user.service.RabbitService; 13 import com.sharp.forward.util.RabbitUtil; 14 15 /** 16 * @author 醉逍遥 17 * 18 */ 19 @Service("rabbitService") 20 @Transactional(readOnly=true) 21 public class RabbitServiceImpl implements RabbitService{ 22 23 private static final Logger logger = LoggerFactory.getLogger(RabbitServiceImpl.class); 24 @Autowired 25 private RabbitUtil util; 26 @Override 27 public void sendObjectMessage(String message) { 28 logger.info("要发送的参数是:------> {}",message); 29 util.sendMessage(message); 30 } 31 }
之前运行一直在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);
}
测试后在管控台看到消息
主要结构
本博主支持并坚持原创,本博客文章将以原创为主。