Home > Back-end >  SpringBoot automatic assembly, need a hand to release the Connection?
SpringBoot automatic assembly, need a hand to release the Connection?

Time:04-01

In view of the remote connection (such as database, the RabbitMq), generally there are two ways,
The first kind of traditional way of use:
 
In view of the remote connection (such as database, the RabbitMq), generally there are two ways,
The first kind of traditional way of use:

//1 create a ConnectionFactory and configure
ConnectionFactory ConnectionFactory=new ConnectionFactory (Host, Port, Username, Password);

//2 create connection through a connection factory
The Connection Connection=connectionFactory. NewConnection ();

//3 create a Channel through the connection
The Channel Channel=connection. CreateChannel ();

//4 sent via Channel data
for(int i=0; I & lt; 5; I++) {
String MSG="Hello RabbitMQ!" ;
Channel. BasicPublish (" ", "test001", null, MSG. GetBytes ());
}

//5 remember to close related connection
Channel. The close ();
connection.close();


The second use SpringBoot automatic assembly

 
@ Configuration
Public class RabbitMQTemplateConfig {
@ Value (" {rabbit. Addresses} ")
Private String ADDRESSES;
@ Value (" {rabbit. Virtual_host} ")
Private String VIRTUAL_HOST;
@ Value (" {rabbit. User_name} ")
Private String USER_NAME;
@ Value (" {rabbit. "} ")
Private String PASSWORD;

@ Bean
Public CachingConnectionFactory CachingConnectionFactory () {
CachingConnectionFactory CachingConnectionFactory=new CachingConnectionFactory ();

CachingConnectionFactory. SetAddresses (ADDRESSES);
CachingConnectionFactory. SetVirtualHost (VIRTUAL_HOST);
CachingConnectionFactory. SetUsername (USER_NAME);
CachingConnectionFactory. SetPassword (PASSWORD);

Return cachingConnectionFactory;
}

@ Bean
Public RabbitTemplate RabbitTemplate () {
RabbitTemplate RabbitTemplate=new RabbitTemplate (cachingConnectionFactory ());
RabbitTemplate. SetMessageConverter (jackson2JsonMessageConverter ());
return rabbitTemplate;
}

@ Bean
Public MessageConverter jackson2JsonMessageConverter () {
Jackson2JsonMessageConverter Jackson2JsonMessageConverter=new Jackson2JsonMessageConverter ();
Return jackson2JsonMessageConverter;
}
}


Then in the second when using SpringBoot automatic assembly, CachingConnectionFactory didn't hand release, is to create CachingConnectionFactory Bean to the IOC, need not release?
  • Related