第一步
<dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit-test</artifactId> <scope>test</scope> </dependency>
第二步 配置文件
spring:
rabbitmq: host: 172.18.0.88 port: 5672 username: guest password: guest listener: simple: concurrency: 10 max-concurrency: 20 prefetch: 5 virtual-host: /
----------------------配置消息属性----------------------------------------
mq: env: local log.user.queue.name: ${mq.env}.log.user.queue #队列名称 log.user.exchange.name: ${mq.env}.log.user.exchange #交换机名称 log.user.routing.key.name: ${mq.env}.log.user.routing.key #路由的key
第三步 新建一个配置类
package com.zzh.elite.config; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import javax.annotation.Resource; @Configuration @Slf4j public class RabbitmqConfig { @Resource private Environment env; @Autowired private CachingConnectionFactory connectionFactory; @Autowired private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer; /** * 单一消费者 * * @return */ @Bean(name = "singleListenerContainer") public SimpleRabbitListenerContainerFactory listenerContainer() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setMessageConverter(new Jackson2JsonMessageConverter()); factory.setConcurrentConsumers(1); factory.setMaxConcurrentConsumers(1); factory.setPrefetchCount(1); //factory.setTxSize(1); factory.setAcknowledgeMode(AcknowledgeMode.AUTO); return factory; } /** * 多个消费者 * * @return */ @Bean(name = "multiListenerContainer") public SimpleRabbitListenerContainerFactory multiListenerContainer() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factoryConfigurer.configure(factory, connectionFactory); factory.setMessageConverter(new Jackson2JsonMessageConverter()); factory.setAcknowledgeMode(AcknowledgeMode.NONE); factory.setConcurrentConsumers(env.getProperty("spring.rabbitmq.listener.concurrency",int.class)); factory.setMaxConcurrentConsumers(env.getProperty("spring.rabbitmq.listener.max-concurrency", int.class)); factory.setPrefetchCount(env.getProperty("spring.rabbitmq.listener.prefetch", int.class)); return factory; } @Bean public RabbitTemplate rabbitTemplate() { connectionFactory.setPublisherConfirms(true); connectionFactory.setPublisherReturns(true); RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMandatory(true); rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause); } }); rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() { @Override public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message); } }); return rabbitTemplate; } //用户操作日志消息模型 @Bean(name = "logUserQueue") public Queue logUserQueue(){ return new Queue(env.getProperty("log.user.queue.name"),true); } @Bean public DirectExchange logUserExchage(){ return new DirectExchange(env.getProperty("log.user.exchange.name"),true,false); } @Bean public Binding logUserBinding(){ return BindingBuilder.bind(logUserQueue()).to(logUserExchage()).with(env.getProperty("log.user.routing.key.name")); } }
第四步 测试
生产者测试
--------------日志实体-------------------------------------
package com.zzh.elite.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class UserLog implements Serializable { private Long id=1l; private Date createTime; private String user; private String password; private String writeValueAsString; public UserLog(String user, String password, String writeValueAsString) { this.user = user; this.password = password; this.writeValueAsString = writeValueAsString; } @Override public String toString() { return "UserLog{" + "createTime=" + createTime + ", user='" + user + '\'' + ", password='" + password + '\'' + ", writeValueAsString='" + writeValueAsString + '\'' + '}'; } }
----------------------controller------------------------------------
@Autowired private RabbitTemplate rabbitTemplate;
@Autowired private Environment env;
@RequestMapping(value = "test/rabbitMq",method = RequestMethod.POST) @ApiOperation("rabbitMq 生产者测试") public ResponseMessage<MysqlTestVO> rabbitMq(@RequestBody MysqlTestDTO mysqlTestDTO){ try { UserLog userLog = new UserLog(mysqlTestDTO.getUser(), "Login", objectMapper.writeValueAsString(mysqlTestDTO));// userLog.setCreateTime(new Date()); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); rabbitTemplate.setExchange(env.getProperty("log.user.exchange.name")); rabbitTemplate.setRoutingKey(env.getProperty("log.user.routing.key.name")); Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(userLog)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build(); message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON); rabbitTemplate.convertAndSend(message); } catch (Exception e) { e.printStackTrace(); } return CommonUtils.okResponseVO(null); }
---------------------------消费者 配置一个监听----------------------------------------------
package com.zzh.elite.listener; import com.fasterxml.jackson.databind.ObjectMapper; import com.zzh.elite.entity.UserLog; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Slf4j public class CommonMqListener { @Autowired private ObjectMapper objectMapper; /** * 监听消费用户日志 * @param message */ @RabbitListener(queues = "${log.user.queue.name}",containerFactory = "singleListenerContainer") public void consumeUserLogQueue(Message message){ try { UserLog userLog=objectMapper.readValue(new String(message.getBody()),UserLog.class); log.info("监听消费用户日志 监听到消息: {} ",userLog); }catch (Exception e){ e.printStackTrace(); } } }
可通过controller插入消息 在界面或后台日志查看消息是否消费