Introduction to rabbitmq:
MQ is the full name of Message Queue. Message Queue (MQ) is a method of communication between applications and applications. Applications communicate by reading and writing queued messages (data for applications) without a dedicated connection to link them. Message delivery refers to communication between programs by sending data in messages, rather than by directly calling each other, direct calls are usually used in techniques such as remote procedure calls. Queuing refers to the application communicating through a queue. The use of queues eliminates the requirement that both the receiving and sending application execute simultaneously. Among them, the more mature MQ products are IBM WEBSPHERE MQ.
The content of this section is that when a user registers, the email address is first stored in the rabbitmq queue, and then returned to the user for successful registration; then the receiver of the message queue obtains the message from the queue and sends an email to the user.
1. Introduction to RabbitMQ
If you don’t know about rabbitmq before, it is recommended to take a look at RabbitMQ Quick (Quick Manual).
1. Installation of rabbitmq on mac.
2. A brief introduction to rabbitmq.
Producer: Responsible for sending messages to Exchange.
Exchange: According to certain policies, it is responsible for storing messages into the specified queue.
Queue: Responsible for saving messages.
Consumer: Responsible for extracting messages from the queue.
binding: Responsible for the association mapping of Exchange and queues. Exchange and queue are many-to-many relationships.
2. 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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--1. Configure the connection factory. If you do not configure host, port, username, password, then localhost:5672, guest/guest--> <!--<connection-factory id="connectionFactory" />--> <connection-factory id="connectionFactory" host="localhost" port="5672" username="everSeeker" password="333" /> <!--2. Configure queue queues, Exchange, and binding that combines them together--> <!--In queue and exchange, there is an important attribute durable, which defaults to true, which can prevent data loss after downtime. --> <!--In listener-container, there is acknowledge attribute, which is defaulted to auto, that is, the consumer must have a reply after successfully processing the message. If the consumer program encounters an exception or crashes, the message will be re-placed back to the queue--> <admin connection-factory="connectionFactory" /> <queue id="userAlertEmailQueue" name="user.alerts.email" durable="true" /> <queue id="userAlertCellphoneQueue" name="user.alerts.cellphone" /> <!--durable defaults to true--> <!--There are 4 types of standard AMQP Exchange: Direct, Topic, Headers, Fanout, Choose according to actual needs. --> <!--Direct: If the routing key of the message directly matches the routing key of the bingding, the message will be routed to the queue. --> <!--Topic: If the routing key of the message matches the routing key of the bingding, 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: No matter what the routing key of the message and the header/value of the parameter table are, 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's 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" /> <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 configure connection-factory and use the default guest/guest account password, org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. The solution 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, create a new user, administrator permissions.
3. Virtual Hosts, set new users to allow access.
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) { //convertAndSend(String exchange, String routingKey, Object object), encapsulate the object object into a Message object, and send it 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);} 3. Send emails through javax.mail
1. Introduce dependency packages.
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version></dependency>
2. Configure mail server information.
@Beanpublic MailSender mailSender(Environment env) { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); //If it is a normal 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 mail server adopts SSL authentication, add the following configurations, 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 email.
@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("[email protected]"); message.setTo(to); message.setSubject(user.getUsername() + "Message Confirmation"); message.setText(user.toString()); mailSender.send(message); }} 4. The consumer can call the sending email method.
1. References: Spring Practical Practice (4th Edition).
2. The complete code is in github, address: https://github.com/everseeker0307/register.
The above is the message queue (rabbitmq) sending email function of Spring Learning Notes 3 introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!