|
| 1 | +package com.javatmp.demo.mq.config; |
| 2 | + |
| 3 | +import org.springframework.amqp.core.*; |
| 4 | +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; |
| 5 | +import org.springframework.amqp.rabbit.connection.ConnectionFactory; |
| 6 | +import org.springframework.amqp.rabbit.core.RabbitTemplate; |
| 7 | +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; |
| 8 | +import org.springframework.amqp.support.converter.MessageConverter; |
| 9 | +import org.springframework.beans.factory.annotation.Value; |
| 10 | +import org.springframework.context.annotation.Bean; |
| 11 | +import org.springframework.context.annotation.Configuration; |
| 12 | + |
| 13 | +@Configuration |
| 14 | +public class RabbitMQConfig { |
| 15 | + |
| 16 | + @Value("${spring.rabbitmq.queue}") |
| 17 | + private String queue; |
| 18 | + |
| 19 | + @Value("${spring.rabbitmq.exchange}") |
| 20 | + private String exchange; |
| 21 | + |
| 22 | + @Value("${spring.rabbitmq.routingkey}") |
| 23 | + private String routingKey; |
| 24 | + |
| 25 | + @Value("${spring.rabbitmq.username}") |
| 26 | + private String username; |
| 27 | + |
| 28 | + @Value("${spring.rabbitmq.password}") |
| 29 | + private String password; |
| 30 | + |
| 31 | + @Value("${spring.rabbitmq.host}") |
| 32 | + private String host; |
| 33 | + |
| 34 | + @Bean |
| 35 | + Queue queue() { |
| 36 | + return new Queue(queue, true); |
| 37 | + } |
| 38 | + |
| 39 | + @Bean |
| 40 | + Exchange myExchange() { |
| 41 | + return ExchangeBuilder.directExchange(exchange).durable(true).build(); |
| 42 | + } |
| 43 | + |
| 44 | + @Bean |
| 45 | + Binding binding() { |
| 46 | + return BindingBuilder |
| 47 | + .bind(queue()) |
| 48 | + .to(myExchange()) |
| 49 | + .with(routingKey) |
| 50 | + .noargs(); |
| 51 | + } |
| 52 | + |
| 53 | + @Bean |
| 54 | + public ConnectionFactory connectionFactory() { |
| 55 | + CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(host); |
| 56 | + cachingConnectionFactory.setUsername(username); |
| 57 | + cachingConnectionFactory.setPassword(password); |
| 58 | + return cachingConnectionFactory; |
| 59 | + } |
| 60 | + |
| 61 | + @Bean |
| 62 | + public MessageConverter jsonMessageConverter() { |
| 63 | + return new Jackson2JsonMessageConverter(); |
| 64 | + } |
| 65 | + |
| 66 | + @Bean |
| 67 | + public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { |
| 68 | + final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); |
| 69 | + rabbitTemplate.setMessageConverter(jsonMessageConverter()); |
| 70 | + return rabbitTemplate; |
| 71 | + } |
| 72 | +} |
0 commit comments