Spring Learning Note 3 Message Queuing (RABBITMQ) Send mail feature _java

Source: Internet
Author: User
Tags message queue object object rabbitmq

RABBITMQ Introduction:

MQ is called Message queue, which is a method of application-wide communication. Applications communicate by reading and writing messages to and from queues (for application data) without having to link them with a private connection. Messaging refers to the fact that programs communicate with each other by sending data in a message, rather than by directly calling each other, a direct call is usually a technique for a remote procedure call. Queuing refers to the application's communication through queues. The use of queues eliminates the need for both receiving and sending applications to execute concurrently. One of the more mature MQ products is IBM WEBSPHERE MQ.

The content of this section is that when a user registers, the mailbox address is first deposited in the RABBITMQ queue, then returned to the user for successful registration, then the recipient of the message queue gets the message from the queue and sends the message to the user.

First, RABBITMQ Introduction

If you do not understand the RABBITMQ before, the recommended first look at RABBITMQ quick (Quick manual).

1, RABBITMQ on the MAC installation.

2, Rabbitmq simple introduction.

Producer: Responsible for sending messages to exchange.

Exchange: According to a certain policy, it is responsible for storing messages in the specified queue.

Queues queue: is responsible for saving messages.

Consumer: is responsible for extracting messages from the queue.

Binding: Responsible for Exchange and queue Association mappings, Exchange and queues are many-to-many relationships.

Ii. the implementation of RABBITMQ in spring

1, the introduction of the dependency package.

<dependency>
   <groupId>org.springframework.amqp</groupId>
   <artifactId> spring-amqp</artifactid>
   <version>1.6.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.amqp</groupId>
   <artifactId> Spring-rabbit</artifactid>
   <version>1.6.0.RELEASE</version>
  

2, RABBITMQ configuration file.

<?xml version= "1.0" encoding= "UTF-8"?> <beans:beans xmlns= "Http://www.springframework.org/schema/rabbit"
    xmlns:beans= "Http://www.springframework.org/schema/beans" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/ Spring-rabbit.xsd Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/
 Spring-beans.xsd "> <!--1, configure the connection factory, if you do not configure host, port, username, PASSOWRD, the default value localhost:5672, guest/guest--> <!--<connection-factory id= "ConnectionFactory"/>--> <connection-factory id= "ConnectionFactory" host = "localhost" port= "5672" username= "Everseeker" password= "333"/> <!--2, configuring queue queues, Exchange, and putting them Binding--> <!--in the queue and exchange, there is an important attribute durable, the default is true, to prevent data loss after downtime. --> <!--in Listener-container, there are acknowledge properties, the default is auto, that is, consumers must have a reply after the message is successfully processed, if the consumerIf an exception or outage occurs, the message is returned back to the queue--> <admin connection-factory= "connectionfactory/> <queue" id= "Name=" User.alerts.email "durable=" true "/> <queue id=" Useralertcellphonequeue "name=" User.alerts.cellphone "/ > <!--durable defaults to true--> <!--standard AMQP exchange has 4 kinds: Direct, Topic, Headers, Fanout, depending on the actual need to choose. --> <!--Direct: If the routing key of the message matches the Bingding routing key directly, the message will be routed to the queue. --> <!--Topic: If the routing key of the message matches the wildcard match to Bingding's routing key, the message will be routed to the queue. --> <!--Headers: If the header information and values in the message parameter table match the binding parameter table, the message will be routed to the queue. --> <!--fanout: Messages are routed to the queue regardless of the header information/value of the routing key and the parameter table. --> <direct-exchange name= "User.alert.email.exchange" durable= "true" > <bindings> <binding queue= "u Ser.alerts.email "/> <!--The default routing key is the same as the name of the queue--> </bindings> </direct-exchange> <direct-ex Change name= "User.alert.cellphone.exchange" > <bindings> <binding queue= "User.alerts.cellphone"/> &Lt;/bindings> </direct-exchange> <!--3, configuring rabbittemplate to send messages--> <template id= "Rabbittemplate" conn ection-factory= "ConnectionFactory"/> <!--4, configuring listener containers and listeners to receive messages--> <beans:bean id= "Userlistener" class= " Com.everSeeker.alerts.UserAlertHandler "/> <listener-container connection-factory=" ConnectionFactory " acknowledge= "Auto" > <listener ref= "Userlistener" method= "Handleuseralerttoemail" queues= "UserAlertEmailQ" Ueue "/> <listener ref=" Userlistener "method=" Handleuseralerttocellphone "queues=" UserAlertCellphoneQueu  E "/> </listener-container> </beans:beans>

If you configure connection-factory with the default guest/guest account password, you may receive a org.springframework.amqp.AmqpAuthenticationException: Com.rabbitmq.client.authenticationfailureexception:access_refused-login was refused using authentication mechanism PLAIN. For details see the broker logfile. Error prompts, the workaround is to create a new user with administrator privileges and allow access to the virtual host.

The steps are as follows:

1, open http://localhost:15672/

2, admin--> users, new user, Administrator authority.

3, Virtual Hosts, set up new users to allow access.

3. Producers send messages to exchange.

@Service ("Useralertservice") Public
class Useralertserviceimpl implements Useralertservice {
 private Rabbittemplate Rabbit;
 @Autowired public
 Useralertserviceimpl (rabbittemplate rabbit) {
  this.rabbit = rabbit;
 }
 public void Senduseralerttoemail (user user) {
  //convertandsend (string Exchange, String Routingkey, Object object) After the object objects are encapsulated into a message object, send to Exchange
  rabbit.convertandsend ("User.alert.email.exchange", "User.alerts.email", user);
 }

4, configure consumers to receive messages.

public class Useralerthandler {public
 void Handleuseralerttoemail (user user) {
  System.out.println (user);
}

Third, through the javax.mail to send mail

1, the introduction of the dependency package.

<dependency>
 <groupId>javax.mail</groupId>
 <artifactId>mail</artifactId>
 <version>1.4.7</version>

2, configure mail server information.

@Bean public
MailSender MailSender (Environment env) {
 Javamailsenderimpl mailsender = new Javamailsenderimpl () ;
 If the ordinary mailbox, non-SSL authentication, such as 163 mailbox
 Mailsender.sethost (Env.getproperty ("Mailserver.host"));
 Mailsender.setport (Integer.parseint) (Env.getproperty ("Mailserver.port"));
 Mailsender.setusername (Env.getproperty ("Mailserver.username"));
 Mailsender.setpassword (Env.getproperty ("Mailserver.password"));
 Mailsender.setdefaultencoding ("Utf-8");
 If the mail server uses SSL authentication, add the following configuration, such as Gmail mailbox, QQ mailbox
 Properties Props = new properties ();
 Props.put ("Mail.smtp.auth", "true");
 Props.put ("Mail.smtp.starttls.enable", "true");
 Props.put ("Mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
 Props.put ("Mail.smtp.socketFactory.port", "465");
 Mailsender.setjavamailproperties (props);
 return mailsender;

3, Send mail.

@Component ("Usermailservice") Public
class Usermailserviceimpl implements Usermailservice {
 private MailSender MailSender;
 @Autowired public
 Usermailserviceimpl (MailSender mailsender) {
  this.mailsender = MailSender;
 }
 public void Sendsimpleusermail (String to, user user) {
  simplemailmessage message = new Simplemailmessage ();
  Message.setfrom ("xxxxxxxx@qq.com");
  Message.setto (to);
  Message.setsubject (User.getusername () + "Information confirmation");
  Message.settext (User.tostring ());
  Mailsender.send (message);
 }

4, the consumer calls Send mail method can.

1, Reference: Spring Combat (4th edition).

2, the complete code in GitHub, address: Https://github.com/everseeker0307/register.

The above is a small set to introduce the Spring Learning Note 3 Message queue (RABBITMQ) to send mail function, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.