• SpringBoot实用开发篇复习3


    我们之前学习了数据访问层的解决方案,包括关系数据库和非关系数据库,这一篇我们重点学校SpringBoot整合第三方技术,下面一起努力学习吧。

    目录

    一、整合第三方技术

    1.1、缓存

    1.1.1、缓存的作用

    1.1.2、SpringBoot缓存使用方式

     1.1.3、手机验证码案例(默认缓存simple)

    1.1.4、变更缓存encache

    1.1.5、变更缓存redis

    1.1.6、缓存变更memcached

    1.1.7、jetcache缓存

     1.1.8、j2cache缓存

    ​  1.2、任务

    1.2.1、SpringBoot整合quartz

    1.2.2、SpringBoot整合Task

    1.3、邮件(SpringBoot整合Javamail)

    1.3.1、发送简单邮件

    1.3.2、发送多部邮件

    1.4、消息

    1.4.1、消息简介

    1.4.2、SpringBoot整合ActiveMQ

     1.4.3、SpringBoot整合RabbitMQ

    1.4.4、SpringBoot整合RocketMQ


    一、整合第三方技术

    1.1、缓存

    1.1.1、缓存的作用

    缓存是在应用软件和数据库之间的一个数据临时存储介质,使用缓存可以有效地减少低速数据读取的次数(例如:磁盘IO),提高系统性能。缓存不仅可以用于提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间。

    1.1.2、SpringBoot缓存使用方式

    首先需要在pom.xml文件中导入缓存对应的坐标依赖,如下:

     然后在启动类使用@EnableCaching注解启动缓存,如下:

     在具体的操作中使用缓存,将相应的操作结果放入缓存中,具体如下:

     1.1.3、手机验证码案例(默认缓存simple)

    1)浏览器传入手机号,返回6位验证码,将验证码存入缓存。

    2)浏览器传入传入手机号和验证码,返回比对缓存中的验证码和传入的验证码结果是否一致。

    首先配置坐标依赖,如下:

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <parent>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-parentartifactId>
    8. <version>2.7.5version>
    9. <relativePath/>
    10. parent>
    11. <groupId>com.codegroupId>
    12. <artifactId>codeartifactId>
    13. <version>0.0.1-SNAPSHOTversion>
    14. <name>codename>
    15. <description>Demo project for Spring Bootdescription>
    16. <properties>
    17. <java.version>1.8java.version>
    18. properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.bootgroupId>
    22. <artifactId>spring-boot-starterartifactId>
    23. dependency>
    24. <dependency>
    25. <groupId>org.projectlombokgroupId>
    26. <artifactId>lombokartifactId>
    27. <version>1.18.24version>
    28. <scope>providedscope>
    29. dependency>
    30. <dependency>
    31. <groupId>org.springframework.bootgroupId>
    32. <artifactId>spring-boot-starter-webartifactId>
    33. dependency>
    34. <dependency>
    35. <groupId>org.springframework.bootgroupId>
    36. <artifactId>spring-boot-starter-cacheartifactId>
    37. dependency>
    38. <dependency>
    39. <groupId>org.springframework.bootgroupId>
    40. <artifactId>spring-boot-starter-testartifactId>
    41. <scope>testscope>
    42. dependency>
    43. dependencies>
    44. <build>
    45. <plugins>
    46. <plugin>
    47. <groupId>org.springframework.bootgroupId>
    48. <artifactId>spring-boot-maven-pluginartifactId>
    49. plugin>
    50. plugins>
    51. build>
    52. project>

    然后,创建实体类,使用lomok。

    1. import lombok.Data;
    2. @Data
    3. public class SMCode {
    4. private String tel ;
    5. private String code ;
    6. }

    业务层,创建接口和实现类,用于将密码转化成验证码存入缓存,并对比下次传入的验证码和缓存中的验证码是否一致。

    1. import com.code.domain.SMCode;
    2. public interface SMService {
    3. public String sendToCodeSM(String tel) ;
    4. public boolean check(SMCode smCode) ;
    5. }
    1. import com.code.domain.SMCode;
    2. import com.code.utils.CodeUtils;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.cache.annotation.CachePut;
    5. import org.springframework.stereotype.Service;
    6. @Service
    7. public class SMServiceImpl implements SMService {
    8. @Autowired
    9. private CodeUtils codeUtils ;
    10. @Override
    11. @CachePut(value = "smsCode", key = "#tel")
    12. public String sendToCodeSM(String tel) {
    13. String code = codeUtils.generator(tel) ;
    14. return code ;
    15. }
    16. @Override
    17. public boolean check(SMCode smCode) {
    18. String code = smCode.getCode() ;
    19. String smsCode = codeUtils.get(smCode.getTel()) ;
    20. return code.equals(smsCode);
    21. }
    22. }

    业务层需要使用一个工具类,封装成bean,该工具类用于将密码转换成验证码以及根据手机号读取缓存中的验证码,如下:

    1. import org.springframework.cache.annotation.Cacheable;
    2. import org.springframework.stereotype.Component;
    3. @Component
    4. public class CodeUtils {
    5. static String [] arr = {"00000","0000","000","00","0",""} ;
    6. public String generator(String tel){
    7. int hash = tel.hashCode() ;
    8. int encryption = 20226666 ;
    9. long result = hash ^ encryption ;
    10. long time = System.currentTimeMillis() ;
    11. result = result ^ time ;
    12. long code = result % 100000 ;
    13. code = code < 0 ? -code : code ;
    14. return arr[String.valueOf(code).length()-1] + code ;
    15. }
    16. @Cacheable(value = "smsCode" , key = "#tel")
    17. public String get(String tel){
    18. return null ;
    19. }
    20. /* public static void main(String[] args) {
    21. System.out.println(new CodeUtils().generator("19825069651"));
    22. }*/
    23. }

    在表现层调用业务层的接口,实现相应的请求和响应功能。

    1. import com.code.domain.SMCode;
    2. import com.code.service.SMService;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.web.bind.annotation.*;
    5. @RestController
    6. @RequestMapping("/sms")
    7. public class SMController {
    8. @Autowired
    9. private SMService smService ;
    10. @GetMapping
    11. public String getCode(String tel){
    12. String code = smService.sendToCodeSM(tel) ;
    13. return code ;
    14. }
    15. @PostMapping
    16. public boolean checkCode(SMCode smCode){
    17. return smService.check(smCode) ;
    18. }
    19. }

    最后需要在启动类加上启动缓存功能的注解EnableCaching,如下:

    1. import org.springframework.boot.SpringApplication;
    2. import org.springframework.boot.autoconfigure.SpringBootApplication;
    3. import org.springframework.cache.annotation.EnableCaching;
    4. @SpringBootApplication
    5. @EnableCaching
    6. public class CodeApplication {
    7. public static void main(String[] args) {
    8. SpringApplication.run(CodeApplication.class, args);
    9. }
    10. }

    1.1.4、变更缓存encache

    首先需要在配置文件中加入坐标依赖,如下:

    1. <dependency>
    2. <groupId>net.sf.ehcachegroupId>
    3. <artifactId>ehcacheartifactId>
    4. dependency>

    然后需要配置ehchache.xml,其中根据缓存名称加载缓存,可以设置缓存有效时间等。

    1. "1.0" encoding="UTF-8"?>
    2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd"
    4. updateCheck="false">
    5. <diskStore path="D:\ehcache" />
    6. <defaultCache
    7. eternal="false"
    8. diskPersistent="false"
    9. maxElementsInMemory="1000"
    10. overflowToDisk="false"
    11. timeToIdleSeconds="60"
    12. timeToLiveSeconds="60"
    13. memoryStoreEvictionPolicy="LRU" />
    14. <cache
    15. name="smsCode"
    16. eternal="false"
    17. diskPersistent="false"
    18. maxElementsInMemory="1000"
    19. overflowToDisk="false"
    20. timeToIdleSeconds="60"
    21. timeToLiveSeconds="60"
    22. memoryStoreEvictionPolicy="LRU" />
    23. ehcache>

    然后需要在.yml配置类中设置使用encache缓存即可,如下:

    1. spring:
    2. cache:
    3. type: ehcache

    1.1.5、变更缓存redis

    首先早pom.xml文件中导入redis的坐标依赖,如下:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-redisartifactId>
    4. dependency>

    然后配置redis在.yml文件中配置redis即可,如下:

    1. spring:
    2. redis:
    3. host: localhost
    4. port: 6379
    5. cache:
    6. type: redis
    7. redis:
    8. use-key-prefix: true
    9. key-prefix: sms_
    10. time-to-live: 20s #有效时长
    11. cache-null-values: false

    1.1.6、缓存变更memcached

    首先下载memcahed,然后解压就可以,然后以管理员身份打开memcached,输入指令切换到memcahed解压的文件夹下,安装和启动memcached即可。

     下面在SpringBoot中整合memcached缓存,首先在pom.xml文件中加载坐标依赖,具体如下:

     在.yml文件中做该缓存的必要配置,如下:

    然后,读取配置类,并封装成bean,如下:

     创建客户端配置类,具体如下:

     注入客户端对象,进行修改值和查询值,如下:

    1.1.7、jetcache缓存

    jetCache实现了对SpringCache进行了封装,在原有功能的基础之上实现了多级缓存、缓存统计、自动刷新、自动调用、数据报表等功能。

     1)jetcache远程缓存

    首先配置坐标依赖,需要把之前的redis坐标依赖删除,否则会导致循环依赖。

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <parent>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-parentartifactId>
    8. <version>2.4.5version>
    9. <relativePath/>
    10. parent>
    11. <groupId>com.codegroupId>
    12. <artifactId>codeartifactId>
    13. <version>0.0.1-SNAPSHOTversion>
    14. <name>codename>
    15. <description>Demo project for Spring Bootdescription>
    16. <properties>
    17. <java.version>1.8java.version>
    18. properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.bootgroupId>
    22. <artifactId>spring-boot-starterartifactId>
    23. dependency>
    24. <dependency>
    25. <groupId>org.projectlombokgroupId>
    26. <artifactId>lombokartifactId>
    27. dependency>
    28. <dependency>
    29. <groupId>org.springframework.bootgroupId>
    30. <artifactId>spring-boot-starter-webartifactId>
    31. dependency>
    32. <dependency>
    33. <groupId>com.alicp.jetcachegroupId>
    34. <artifactId>jetcache-starter-redisartifactId>
    35. <version>2.6.2version>
    36. dependency>
    37. <dependency>
    38. <groupId>org.springframework.bootgroupId>
    39. <artifactId>spring-boot-starter-testartifactId>
    40. <scope>testscope>
    41. dependency>
    42. dependencies>
    43. <build>
    44. <plugins>
    45. <plugin>
    46. <groupId>org.springframework.bootgroupId>
    47. <artifactId>spring-boot-maven-pluginartifactId>
    48. plugin>
    49. plugins>
    50. build>
    51. project>

    然后再.yml文件中进行相关配置,如下:
     

    1. jetcache:
    2. remote:
    3. default:
    4. type: redis
    5. host: localhost
    6. port: 6379
    7. poolConfig:
    8. maxTotal: 50

    使用缓存,如下所示。

    1. import com.alicp.jetcache.Cache;
    2. import com.alicp.jetcache.anno.CreateCache;
    3. import com.code.domain.SMCode;
    4. import com.code.utils.CodeUtils;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.concurrent.TimeUnit;
    8. @Service
    9. public class SMServiceImpl implements SMService {
    10. @Autowired
    11. private CodeUtils codeUtils ;
    12. //设置缓存有效时长未20s
    13. @CreateCache(name = "jetCache", expire = 20, timeUnit = TimeUnit.SECONDS)
    14. public Cache jetCache ;
    15. @Override
    16. public String sendToCodeSM(String tel) {
    17. String code = codeUtils.generator(tel) ;
    18. jetCache.put(tel, code);
    19. return code ;
    20. }
    21. @Override
    22. public boolean check(SMCode smCode) {
    23. String code = smCode.getCode() ;
    24. String smsCode = jetCache.get(smCode.getTel()) ;
    25. return code.equals(smsCode);
    26. }
    27. }

    需要在启动类加上启动注解,如下所示。

    1. @SpringBootApplication
    2. @EnableCreateCacheAnnotation
    3. public class CodeApplication {
    4. public static void main(String[] args) {
    5. ConfigurableApplicationContext context = SpringApplication.run(CodeApplication.class, args);
    6. }
    7. }

    最后打开redis服务端,使用postman发送web请求测试即可。

    2)jetcache本地缓存

    本地方案和远程方案可以共存,可以设置选择使用哪一种方案,只需要在.yml文件中配置本地缓存

    1. jetcache:
    2. local:
    3. default:
    4. type: linkedhashmap
    5. keyConvertor: fastjson

    然后在业务层使用缓存的时候,设置为使用本地缓存即可。

    1. import com.alicp.jetcache.Cache;
    2. import com.alicp.jetcache.anno.CacheType;
    3. import com.alicp.jetcache.anno.CreateCache;
    4. import com.code.domain.SMCode;
    5. import com.code.utils.CodeUtils;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.concurrent.TimeUnit;
    9. @Service
    10. public class SMServiceImpl implements SMService {
    11. @Autowired
    12. private CodeUtils codeUtils ;
    13. //设置缓存有效时长未20s,设置为只用本地缓存
    14. @CreateCache(name = "jetCache1", expire = 20, timeUnit = TimeUnit.SECONDS, cacheType = CacheType.LOCAL)
    15. public Cache jetCache ;
    16. @Override
    17. public String sendToCodeSM(String tel) {
    18. String code = codeUtils.generator(tel) ;
    19. jetCache.put(tel, code);
    20. return code ;
    21. }
    22. @Override
    23. public boolean check(SMCode smCode) {
    24. String code = smCode.getCode() ;
    25. String smsCode = jetCache.get(smCode.getTel()) ;
    26. return code.equals(smsCode);
    27. }
    28. }

    3)jetcache方法缓存

    首先需要在启动类加上方法注解,开启方法缓存,方法所在的包需要指定。

     下面就可以启用具体的缓存方法注解,查询的注解为@Cached,刷新的注解为@CacheRefresh,添加的注解为@CacheUpdate,删除的注解为@CacheInvalidate

    因为需要保证缓存对象的序列化,才能操作方法缓存,所以需要对实体类实现序列化,并在配置类中设置序列化和反序列化的类型均为Java类型。

     1.1.8、j2cache缓存

    首先需要加入j2cache相关坐标,主要包含三个坐标,如下所示。

     然后配置j2cache,设置j2cache配置文件的位置。

    创建配置文件j2cache.properties,配置一级缓存和二级缓存以及一级缓存到二级缓存的发送方式。

    将缓存对象进行注入,然后使用缓存对象进行缓存的set和get操作,如下:

    1.2、任务

    1.2.1、SpringBoot整合quartz

    我们在整合框架之前先看一下下面四个概念,工作和工作明细是比较容易理解的,触发器是触发工作的,调度器则是将工作和触发器绑定到一起,不同触发器触发不同的工作明细。

     首先导入SpringBoot整合Quartz的坐标。

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-quartzartifactId>
    4. dependency>

    定义具体要执行的任务。

    1. import org.quartz.JobExecutionContext;
    2. import org.quartz.JobExecutionException;
    3. import org.springframework.scheduling.quartz.QuartzJobBean;
    4. public class MyQuartz extends QuartzJobBean {
    5. @Override
    6. protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    7. System.out.println("quartz take run...");
    8. }
    9. }

    定义工作明细和触发器,并绑定它们之间的关系。

    1. import com.q.quartz.MyQuartz;
    2. import org.quartz.*;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.Configuration;
    5. @Configuration
    6. public class QuartzConfig {
    7. @Bean //绑定具体的工作
    8. public JobDetail printJobDetail(){
    9. return JobBuilder.newJob(MyQuartz.class).storeDurably().build() ;
    10. }
    11. @Bean //绑定对应的工作明细
    12. public Trigger printTrigger(){
    13. ScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?") ;
    14. return TriggerBuilder.newTrigger().forJob(printJobDetail()).withSchedule(scheduleBuilder).build() ;
    15. }
    16. }

    1.2.2、SpringBoot整合Task

    首先在启动类中使用EnableScheduling开启定时任务功能,如下:

    1. import org.springframework.boot.SpringApplication;
    2. import org.springframework.boot.autoconfigure.SpringBootApplication;
    3. import org.springframework.scheduling.annotation.EnableScheduling;
    4. @SpringBootApplication
    5. @EnableScheduling //开启定时任务功能
    6. public class QuartzApplication {
    7. public static void main(String[] args) {
    8. SpringApplication.run(QuartzApplication.class, args);
    9. }
    10. }

    然后,定义一个Bean,设置定时任务和定时周期就可以了,如下:

    1. import org.springframework.scheduling.annotation.Scheduled;
    2. import org.springframework.stereotype.Component;
    3. @Component
    4. public class MyTask {
    5. //设置定时执行的任务,并设置执行周期
    6. @Scheduled(cron = "0/5 * * * * ?")
    7. public void printLog(){
    8. System.out.println(Thread.currentThread().getName() + " is running");
    9. }
    10. }

    1.3、邮件(SpringBoot整合Javamail)

    1.3.1、发送简单邮件

    我们首先来看一下电子邮件中的三个协议,学过计算机网络的对这个应该都比较熟悉了。

    发送邮件的过程如下,首先导入坐标,具体如下:

    需要配置javaMail,配置过程中邮件服务器供应商需要写清楚,邮箱账号和密码要写清楚,这个 密码是从邮件获取的授权码,点击如下开启,发送短信到指定账号即可获取授权码。

    对于业务层,也就是邮件客户端需要怎么写呢,具体如下,首先需要定义发件人、收件人等信息,然后使用注入的JavaMailSender对象进行邮件发送。

     

    1.3.2、发送多部邮件

    这一部分只需要修改业务层的代码,实现邮件附件的发送,以及超链接的发送等。

    具体就不展开了。

    1.4、消息

    1.4.1、消息简介

    消息分为发送方和接收方,也称为生产者和消费者,消息又分为同步消息和异步消息,同步消息必须有响应,异步消息不需要有响应也可以的。

    浏览器发送请求,业务系统会把请求先发送给MQ(消息队列),子业务系统在从MQ中获取相应的要执行的工作,这样的话就可以有效地降低业务系统的压力了,具体如下所示:

    我们先了解一下JMS消息模型,它包含多种消息类型,我们常用的还是字节类型的消息,常用的模型是发布订阅模式。JMS是规范消息开发的API。

     AMQP是规定消息传递的格式,是一种高级消息队列协议,如下所示:

    我们在接下来主要学习四个消息队列的实现,分别是:ActiveMQ、RabbitMQ、RocketMQ、kafka.

    1.4.2、SpringBoot整合ActiveMQ

    1)ActiveMQ的下载与安装

    首先在官网进行下载安装即可,官网地址如下:ActiveMQ

    下载后解压缩,然后双击activemq.exe即可启动服务,通过地址可以访问ActiveMQ的服务器,如下:

     进入到如下界面,说明ActiveMQ服务器启动成功。

     2)SpringBoot整合ActiveMQ

    首先导入mq坐标依赖,如下所示。

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-activemqartifactId>
    4. dependency>

    然后在.yml文件中进行服务器的配置,如下:

    1. spring:
    2. activemq:
    3. broker-url: tcp://localhost:61616
    4. jms:
    5. template:
    6. default-destination: mq
    7. #pub-sub-domain: true 可以在这里设置发布订阅模式

    使用注入的JmsMessageServiceTemplate进行生产消息和接收消息,为了使生产的消息可以立刻被消费,我们一般会设置监听器监听,然后立刻消费。

    1. import com.mq.service.MessageService;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.jms.core.JmsMessagingTemplate;
    4. import org.springframework.stereotype.Service;
    5. @Service
    6. public class MessageServiceActivemqImpl implements MessageService {
    7. @Autowired
    8. private JmsMessagingTemplate jmsMessagingTemplate ;
    9. @Override
    10. public void sendMessage(String id) {
    11. System.out.println("待发送的消息已纳入处理队列:id" + id);
    12. jmsMessagingTemplate.convertAndSend("order.queue.id",id);
    13. }
    14. @Override
    15. public String doMessage() {
    16. String id = jmsMessagingTemplate.receiveAndConvert("order.queue.id" , String.class) ;
    17. System.out.println("已经完成发送的业务:id" + id);
    18. return id;
    19. }
    20. }

    监听器的设置如下,用于监听 指定位置的消息。

    1. import org.springframework.jms.annotation.JmsListener;
    2. import org.springframework.messaging.handler.annotation.SendTo;
    3. import org.springframework.stereotype.Component;
    4. @Component
    5. public class MessageListener {
    6. @JmsListener(destination = "order.queue.id") //监听响应位置的消息,用于立刻消费、
    7. @SendTo("order.other.queue.id") //用于
    8. public String receive(String id){
    9. System.out.println("已完成短信业务发送:id" + id);
    10. return "new:" + id ;
    11. }
    12. }

    控制层发送消息和接收消息的代码如下:

    1. import com.mq.service.OrderService;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.PostMapping;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. @RestController
    8. @RequestMapping("/orders")
    9. public class OrderController {
    10. @Autowired
    11. private OrderService orderService ;
    12. @PostMapping("{id}")
    13. public void order(@PathVariable String id){
    14. orderService.order(id);
    15. }
    16. }
    1. import com.mq.service.MessageService;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.web.bind.annotation.GetMapping;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. @RestController
    7. @RequestMapping("/msgs")
    8. public class MessageController {
    9. @Autowired
    10. private MessageService messageService ;
    11. @GetMapping
    12. public String doMessage(){
    13. String id = messageService.doMessage() ;
    14. return id ;
    15. }
    16. }

    使用postman发送和接收请求模拟得到的效果如下:

     1.4.3、SpringBoot整合RabbitMQ

    1)RabbitMQ的安装与配置

    安装和路径配置的过程如下所示,参考这篇文章即可:我们一起来学RabbitMQ 四:RabbitMQ windows 安装 - 知乎

    命令行看到如下消息,则说明安装配置 erlang 环境成功。

     2)直联交换机模式下SpringBoot整合RabbitMQ

    首先导入RabbitMQ的坐标依赖,如下所示:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-amqpartifactId>
    4. dependency>

    在.yml文件中配置mq,具体如下:

    1. spring:
    2. activemq:
    3. broker-url: tcp://localhost:61616
    4. jms:
    5. template:
    6. default-destination: mq
    7. #pub-sub-domain: true 可以在这里设置发布订阅模式
    8. rabbitmq:
    9. host: localhost
    10. port: 5672

    定义消息队列和交换机,并实现队列和交换机进行绑定,具体如下:

    1. import org.springframework.amqp.core.Binding;
    2. import org.springframework.amqp.core.BindingBuilder;
    3. import org.springframework.amqp.core.DirectExchange;
    4. import org.springframework.amqp.core.Queue;
    5. import org.springframework.context.annotation.Bean;
    6. import org.springframework.context.annotation.Configuration;
    7. @Configuration
    8. public class RabbitConfigDirect {
    9. @Bean //消息队列的对象
    10. public Queue directQueue(){
    11. return new Queue("direct_queue") ;
    12. }
    13. @Bean //消息队列的对象
    14. public Queue directQueue2(){
    15. return new Queue("direct_queue2") ;
    16. }
    17. @Bean //交换机
    18. public DirectExchange directExchange(){
    19. return new DirectExchange("directExchange") ;
    20. }
    21. @Bean //将消息队列和交换机进行绑定
    22. public Binding bindingDirect(){
    23. return BindingBuilder.bind(directQueue()).to(directExchange()).with("direct") ;
    24. }
    25. @Bean //将消息队列和交换机进行绑定
    26. public Binding bindingDirect2(){
    27. return BindingBuilder.bind(directQueue2()).to(directExchange()).with("direct2") ;
    28. }
    29. }

    业务层使用注入的AmqpTemplate进行生产消息,如下:

    1. import com.mq.service.MessageService;
    2. import org.springframework.amqp.core.AmqpTemplate;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.stereotype.Service;
    5. @Service
    6. public class MessageServiceRabbitmqDirectImpl implements MessageService {
    7. @Autowired
    8. private AmqpTemplate amqpTemplate ;
    9. @Override
    10. public void sendMessage(String id) { //使用直联交换机发送消息
    11. System.out.println("待发送的消息订单已经纳入处理队列(rabbitmq direct).id :" + id);
    12. amqpTemplate.convertAndSend("directExchange","direct",id);
    13. }
    14. @Override
    15. public String doMessage() {
    16. return null;
    17. }
    18. }

    使用监听器进行监听,消费消息。

    1. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    2. import org.springframework.stereotype.Component;
    3. @Component
    4. public class MessageListener {
    5. //监听消息队列,有消息就可以消费
    6. @RabbitListener(queues = "direct_queue")
    7. public void receive(String id){
    8. System.out.println("已完成短信发送业务(rabbitmq direct).id" + id);
    9. }
    10. }

    使用postman发送消息请求,可以在服务器端看到生成的两个消息队列。

    3)主题模式下的SpringBoot整合RabbitMQ

    该模式和direct模式的区别在于匹配方式的不同,具体如下:

    1.4.4、SpringBoot整合RocketMQ

    1)下载安装RocketMQ

    现在官网下载安装并完成环境变量的配置,具体如下:

    先启动命名服务器,再启动业务服务器,如下:

    2)SpringBoot整合RocketMQ

    首先在pom.xml文件中导入RocketMQ坐标依赖,具体如下: 

    需要在.yml文件中进行配置,先配置命名服务器,在给生产者配置一个组,如下:

    生产消息,使用注入的RocketMQTemplate完成生产消息。

     当然也可以使用异步生产消息方式进行生产消息,具体如下:

    使用监听器的方式进行监听并消费消息,如下:

  • 相关阅读:
    Go连接Redis集群并实现单例,组件go-redis
    JAVA计算机毕业设计牙科诊所信息化管理平台Mybatis+系统+数据库+调试部署
    react如何阻止父容器滚动
    用Python上傳api資料
    系统异常SVC与PendSV指令
    ​美元兑加元价格分析:空头按兵不动 寻求展开大幅整理
    「喜迎华诞」手把手教你用微信小程序给头像带上小旗帜
    【面试普通人VS高手系列】Spring Boot的约定优于配置,你的理解是什么?
    23设计模式之 --------- 什么是设计模式?
    如何正确开启ruoyi-vue-pro的支付模块,
  • 原文地址:https://blog.csdn.net/nuist_NJUPT/article/details/127880863