rabbitmq 用BlockingQueue实现一个连接池,使用springBoot框架
时间: 2024-02-01 16:14:45
浏览: 126
可以使用SpringBoot框架和BlockingQueue实现一个RabbitMQ连接池,具体步骤如下:
1. 创建一个连接池类,用于管理RabbitMQ连接。在这个类中,我们需要定义一个BlockingQueue来存储连接对象,以及一些方法来获取和释放连接。
@Component
public class RabbitMQPool {
@Value("${rabbitmq.host}")
private [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) host;
@Value("${rabbitmq.port}")
private int port;
@Value("${rabbitmq.username}")
private [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) username;
@Value("${rabbitmq.password}")
private [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) password;
@Value("${rabbitmq.virtualhost}")
private [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) virtualHost;
@Value("${rabbitmq.poolSize}")
private int poolSize;
private BlockingQueue<Channel> channelPool;
private ConnectionFactory connectionFactory;
@[pos](https://geek.csdn.net/educolumn/0399089ce1ac05d7729a569fd611cf73?spm=1055.2569.3001.10083)tConstruct
public void init() {
channelPool = new LinkedBlockingQueue<>(poolSize);
connectionFactory = new ConnectionFactory();
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualHost);
public Channel getChannel() throws InterruptedException, TimeoutException, IOException {
Channel channel = channelPool.poll();
if (channel == null) {
Connection connection = connectionFactory.newConnection();
channel = connection.createChannel();
return channel;
public void releaseChannel(Channel channel) {
channelPool.offer(channel);
```