Spring Study Notes 3-Message Queue (rabbitmq), send emails, Study Notes rabbitmq

Source: Internet
Author: User
Tags rabbitmq

Spring Study Notes 3-Message Queue (rabbitmq), send emails, Study Notes rabbitmq

This section stores the email address in the rabbitmq queue and returns it to the user after registration. Then, the receiver of the Message Queue obtains the message from the queue and sends the email to the user.


1. Introduction to RabbitMQ

If you do not know about rabbitmq before, we recommend that you take a look at RabbitMQ Quick (Quick Manual ).

1. rabbitmq installation on mac.

2. A brief introduction to rabbitmq.

Producer: responsible for sending messages to Exchange.

Exchange: stores messages to a specified Queue according to certain policies.

Queue: stores messages.

Consumer: Extracts messages from the queue.

Binding: Responsible for the Association and ing between Exchange and queue. Exchange and queue are many-to-many relationships.


II. Implementation of RabbitMQ in Spring

1. Introduce dependency packages.

<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>        </dependency>

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 host, port, username, passowrd are not configured, the default value is localhost: 5672, guest/guest --><! -- <Connection-factory id = "connectionFactory"/> --> <connection-factory id = "connectionFactory" host = "localhost" port = "5672" username = "everSeeker" password = "333"/><! -- 2. Configure the queue and Exchange, and the binding that combines them --> <! -- In queue and exchange, there is an important attribute durable. The default value is true, which can prevent data loss after downtime. --> <! -- In listener-container, there is the acknowledge attribute. The default value is auto. That is, the consumer must have a response after successfully processing the message. If the consumer program encounters an exception or goes down, the message will be put back into the queue again --><Admin connection-factory = "connectionFactory"/> <queue id = "userAlertEmailQueue" name = "user. alerts. email "durable =" true "/> <queue id =" userAlertCellphoneQueue "name =" user. alerts. cellphone "/> <! -- Durable is true by default --> <! -- Four standard AMQP Exchange types are available: Direct, Topic, Headers, and Fanout, which can be selected based on actual needs. --> <! -- Direct: If the routing key of a message directly matches the routing key of bingding, the message will be routed to the queue. --> <! -- Topic: If the routing key of a message matches the routing key of bingding, the message is routed to the queue. --> <! -- Headers: If the header information and value in the message parameter table match the binding parameter table, the message is routed to the queue. --> <! -- Fanout: regardless of the message's routing key and parameter table header information/value, the message will be routed to the queue. --> <Direct-exchange name = "user. alert. email. exchange "durable =" true "> <bindings> <binding queue =" user. alerts. email "/> <! -- The default routing key is the same as the queue name --> </bindings> </direct-exchange> <direct-exchange name = "user. alert. cellphone. exchange "> <bindings> <binding queue =" user. alerts. cellphone "/> </bindings> </direct-exchange><! -- 3. Configure RabbitTemplate to send messages --><Template id = "rabbitTemplate" connection-factory = "connectionFactory"/><! -- 4. Configure the listener container and listener to receive messages --><Beans: bean id = "userListener" class = "com. everSeeker. alerts. <listener-container connection-factory = "connectionFactory" acknowledge = "auto"> <listener ref = "userListener" method = "handleUserAlertToEmail" queues = "userAlertEmailQueue"/> <listener ref = "userListener" method = "handleUserAlertToCellphone" queues = "userAlertCellphoneQueue"/> </listener-container> </beans: beans>

If you use the default guest/guest Account Password When configuring connection-factory, org may appear. springframework. amqp. amqpAuthenticationException: com. rabbitmq. client. authenticationFailureException: ACCESS_REFUSED-Login was refused using authentication mechanic PLAIN. for details see the broker logfile. the solution is to create a user with administrator permissions and allow access to the VM. The procedure is as follows:

1. Open http: // localhost: 15672/2, Admin --> Users, create a user, and grant administrator permissions. 3. Set Virtual Hosts to allow access by new users.

3. The producer sends a message 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 User ){// ConvertAndSend (String exchange, String routingKey, Object object), encapsulate the object as a Message Object, and send it to exchange rabbit. convertAndSend ("user. alert. email. exchange "," user. alerts. email", User );}}

4. Configure the consumer to receive messages.

public class UserAlertHandler {        public void handleUserAlertToEmail(User user) {        System.out.println(user);}


3. Send an email via javax. mail

1. Introduce dependency packages.

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

2. Configure the email server information.

@ Beanpublic MailSender mailSender (Environment env) {JavaMailSenderImpl mailSender = new JavaMailSenderImpl ();// If it is a common mailbox, non-ssl authentication, etc., 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 email server uses ssl authentication, add the following configurations, such as gmail mailbox and 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 an email.

@ Component ("userMailService") public class usermailserviceimplements 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 () + "confirm information"); Message. setText (user. toString (); mailSender. send (message );}}

4. The consumer can call the mail sending method.


1. References: Spring practice (version 4th ).

2. complete code is available on github at: https://github.com/everseeker0307/register.

Related Article

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.