RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
SpringBoot中怎么利用RabbitMQ实现用户注册

这篇文章给大家介绍SpringBoot中怎么利用RabbitMQ实现用户注册,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

我们提供的服务有:成都网站设计、网站制作、微信公众号开发、网站优化、网站认证、五莲ssl等。为1000+企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的五莲网站制作公司

实现步骤

添加rabbitmq依赖

 org.springframework.boot  spring-boot-starter-amqp

添加rabbitmq配置

spring: rabbitmq:  addresses: 127.0.0.1  username: guest  password: guest  port: 5672

修改controller类

package com.lytw13.demo.controller;import com.lytw13.demo.model.TbUser;import com.lytw13.demo.service.UserService;import com.lytw13.demo.util.MailUtil;import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("user")public class UserController {  @Autowired  UserService userService;  @Autowired  RabbitTemplate rabbitTemplate;  @PostMapping("save")  public void save(@RequestBody TbUser user) {    userService.save(user);    rabbitTemplate.convertAndSend("email.direct","email.direct",user);  }}

修改service实现类

public void save(TbUser user) {    long startTime = System.currentTimeMillis();    userMapper.insert(user);    long endTime = System.currentTimeMillis();    System.out.println("耗时:"+(endTime-startTime));  }  @RabbitListener(queues = "email.direct")  public void sendEmail(TbUser user) {    List fileList = new ArrayList<>();    fileList.add("E:\\others\\MyBlog\\新建文本文档1.txt");    fileList.add("E:\\others\\MyBlog\\新建文本文档.txt");    MailUtil.sendHtmlTemplateMail(user.getEmail(),user.getName(),fileList);  }

现在就完成了,当用户发送注册信息的时候,会推送给rabbitmq,然后我们只需要定义个方法添加上@RabbitListener(queues = "email.direct")注解进行实时监听, 注意主启动类上需要添加@EnableRabbit开启rabbit,当监听到用户注册的时候,不需要一直等待发送邮件成功,就可以先将页面返回给用户,而不是一直等待,页面一直加载不了(浏览器一直转圈),使用户体验变差,这就是用rabbitmq实现异步操作的最简单用法。

关于SpringBoot中怎么利用RabbitMQ实现用户注册就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


网站栏目:SpringBoot中怎么利用RabbitMQ实现用户注册
文章位置:http://scyingshan.cn/article/phohjh.html