1. 程式人生 > >SpringBoot-Rabbitmq操作

SpringBoot-Rabbitmq操作

依賴

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>

配置

spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.host=192.168.31.153
spring.rabbitmq.port=5672

模板

@RunWith(SpringRunner.class)
@SpringBootTest
public class MqApplicationTests {

    @Autowired
    RabbitTemplate rabbitTemplate;

	@Test
	public void rabbitTest(){
        Student student = new Student();
        student.setGender("male");
        student.setAge(99);
        student.setId(12);
        student.
setName("godme"); rabbitTemplate.convertAndSend("amq.direct", "directQueue", student); } }

監聽

  • @EnableRabbit
@EnableRabbit
@SpringBootApplication
public class MqApplication {
	public static void main(String[] args) {
		SpringApplication.run(MqApplication.class, args);
	}
}
  • @RabbitListener
@Service
public class StudentService {
    // 指定監聽佇列
    @RabbitListener(queues = "directQueue")
    public void print(Student student){
        // 發放自動呼叫
        System.err.println(student);
    }
}
  • @RabbitHandler
@Service
@RabbitListener(queues = "directQueue")
public class StudentService {
    @RabbitHandler
    // 同一佇列多種處理
    public void print(Student student){
        System.err.println(student);
    }
}
Student{id=12, name='godme', age=99, gender='male'}

序列化

@Configuration
public class MqConfig {

@Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    return rabbitTemplate;
    }
}
{"id":12,"name":"godme","age":99,"gender":"male"}

Amqp

@RunWith(SpringRunner.class)
@SpringBootTest
public class MqApplicationTests {
    @Autowired
    AmqpAdmin amqpAdmin;
    @Test
    public void adminTest(){
	    amqpAdmin.declareExchange(new FanoutExchange("fanout"));
	    amqpAdmin.declareExchange(new DirectExchange("direct"));
	    amqpAdmin.declareExchange(new TopicExchange("topic"));
	    amqpAdmin.declareExchange(new HeadersExchange("head"));
	    amqpAdmin.deleteExchange("exchangeName");
	    amqpAdmin.declareQueue(new Queue("queueName"));
        // 持久化
        amqpAdmin.declareQueue(new Queue("queueName", true));
	    amqpAdmin.declareBinding(new Binding("queueName", Binding.DestinationType.QUEUE, "exchageName", "routing-key", null));
    }
}