Springboot中使用Rabbitmq的程式碼
阿新 • • 發佈:2019-02-13
使用之前先確認已安裝rabbitmq
首先,在pom.xml中新增依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在application.yml中新增配置程式碼
spring:
rabbitmq:
listener:
simple:
acknowledge-mode : manual
username: guest
password: guest
host: localhost
port: 5672
virtual-host: /
新增配置類,加上@Configuration和@Bean註解後會自動生成一個佇列
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* RabbitMq佇列配置
*/
@Configuration
public class RabbitConfig {
public static final String COIN_QUEUE ="COIN" ;
@Bean
public Queue getCoinQueue(){
return new Queue(COIN_QUEUE,true);
}
}
在要使用的類中新增import
import org.springframework.amqp.rabbit.core.RabbitTemplate;
然後注入模板
@Autowired
private RabbitTemplate rabbitTemplate;
之後就可以加入隊列了,第一個引數是佇列名,第二個引數是內容,可以是任意型別,也可以是物件
this.rabbitTemplate.convertAndSend(RabbitConfig.COIN_QUEUE, "test");//加入佇列
最後是消費者程式碼,
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
@Component
public class Consumer {
/**
* 處理COIN的佇列請求
*/
@RabbitListener(queues = {RabbitConfig.COIN_QUEUE})
public void handleCoinQueue(CoinConsumerEntity consumerEntity, Message message, Channel channel) {
final long deliveryTag = message.getMessageProperties().getDeliveryTag();
try {
//在這裡可以對接收的資料進行處理,包括持久化等操作
channel.basicAck(deliveryTag, false);
} catch (IOException e) {
try {
channel.basicRecover();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}