当前位置: 代码网 > it编程>编程语言>Java > Springboot使用redisson + 自定义注解实现消息的发布订阅(解决方案)

Springboot使用redisson + 自定义注解实现消息的发布订阅(解决方案)

2024年05月26日 Java 我要评论
前言在一些小型场景下,使用mq中间件可能会为原有项目增加不少维护成本,使用redisson实现消息的收发是个不错的选择什么是redisson?官网:redisson: easy redis java

前言

在一些小型场景下,使用mq中间件可能会为原有项目增加不少维护成本,使用redisson实现消息的收发是个不错的选择

什么是redisson?

官网:redisson: easy redis java client with features of in-memory data grid

redisson是一个基于redis的java驻留内存数据网格(in-memory data grid)和分布式锁框架。它提供了一系列的分布式java对象和服务,可以帮助开发者更方便地使用redis作为数据存储和分布式锁的解决方案。

redisson的主要功能包括:

  • 分布式集合:redisson提供了分布式的set、list、queue、deque等集合,可以在分布式环境下进行操作,实现数据共享和协作。
  • 分布式映射:redisson提供了分布式的map、multimap、concurrentmap等映射结构,可以在分布式环境下进行操作,实现数据的存储和共享。
  • 分布式锁:redisson提供了可重入锁、公平锁、读写锁等分布式锁,可以在分布式环境下实现资源的互斥访问,保证数据的一致性和并发安全。
  • 分布式对象:redisson提供了分布式的atomiclong、countdownlatch、semaphore等对象,可以在分布式环境下实现共享状态和协作操作。

redisson的使用场景包括但不限于:

分布式缓存:redisson可以作为分布式缓存的解决方案,将数据存储在redis中,提高数据的读取速度和系统的性能。

分布式锁:redisson可以用于实现分布式锁,保证在分布式环境下对共享资源的互斥访问,避免数据的并发冲突。

分布式任务调度:redisson可以用于实现分布式任务调度,将任务分发到不同的节点上执行,提高系统的并发处理能力。

redisson的优点包括:

简单易用:redisson提供了简洁的api和丰富的文档,使得使用者可以快速上手。

高性能:redisson利用redis的高性能特性,可以实现快速的数据读写和并发操作。

可靠性:redisson提供了分布式锁和数据持久化等机制,保证数据的一致性和可靠性。

redisson的缺点包括:

依赖于redis:redisson需要依赖redis作为数据存储和分布式锁的后端,需要确保redis的可用性和性能。

部署复杂性:redisson的部署和配置相对复杂,需要对redis和redisson的相关参数进行调优和配置。

redisson发布订阅的基本使用

// 创建redisson客户端
redissonclient redisson = redisson.create();
// 获取rtopic对象
rtopic<string> topic = redisson.gettopic("mytopic");
// 发布消息
topic.publish("hello, redisson!");
// 添加监听器
topic.addlistener(string.class, (channel, msg) -> {
    system.out.println("received message: " + msg);
});
// 关闭redisson客户端
redisson.shutdown();

发布和订阅,是我们需要对同一个 topic 进行发布和监听操作。但这个操作的代码是一种手动编码,但在我们实际使用中,如果所有的都是手动编码,一个是非常麻烦,再有一个是非常累人。通过自定义注解,来完成动态监听和将对象动态注入到 spring 容器中,让需要注入的属性,可以被动态注入。

结合自定义注解优雅实现

导入依赖

        <dependency>
            <groupid>org.redisson</groupid>
            <artifactid>redisson-spring-boot-starter</artifactid>
            <version>3.14.1</version>
        </dependency>

编写redisson初始化配置

redis:
  sdk:
    config:
      host: localhost
      port: 6379
      pool-size: 10
      min-idle-size: 5
      idle-timeout: 30000
      connect-timeout: 5000
      retry-attempts: 3
      retry-interval: 1000
      ping-interval: 60000
      keep-alive: true

编写redisson配置类

/**
 * @description redis连接配置
 * @create 2023/12/17 20:48:13
 */
@data
@configurationproperties(prefix = "redis.sdk.config", ignoreinvalidfields = true)
public class redissoncientconfigproperties {
    /** host:ip */
    private string host;
    /** 端口 */
    private int port;
    /** 账密 */
    private string password;
    /** 设置连接池的大小,默认为64 */
    private int poolsize = 64;
    /** 设置连接池的最小空闲连接数,默认为10 */
    private int minidlesize = 10;
    /** 设置连接的最大空闲时间(单位:毫秒),超过该时间的空闲连接将被关闭,默认为10000 */
    private int idletimeout = 10000;
    /** 设置连接超时时间(单位:毫秒),默认为10000 */
    private int connecttimeout = 10000;
    /** 设置连接重试次数,默认为3 */
    private int retryattempts = 3;
    /** 设置连接重试的间隔时间(单位:毫秒),默认为1000 */
    private int retryinterval = 1000;
    /** 设置定期检查连接是否可用的时间间隔(单位:毫秒),默认为0,表示不进行定期检查 */
    private int pinginterval = 0;
    /** 设置是否保持长连接,默认为true */
    private boolean keepalive = true;
}

编写自定义主题注解,用来指定主题

/**
 * @description redisson 消息主题注解
 * @create 2023/12/17 21:56:10
 */
@retention(retentionpolicy.runtime)
@target({elementtype.type})
@documented
public @interface redistopic {
    // 主题名称
    string topic() default "";
}

初始化redisson客户端,注册主题监听

/**
 * @description redis客户端
 * @create 2023/12/17 20:49:41
 */
@configuration
@enableconfigurationproperties(rediscientconfigproperties.class)
public class redisclientconfig {
     public redissonclient redissonclient(configurableapplicationcontext applicationcontext, rediscientconfigproperties properties) {
        config config = new config();
        config.usesingleserver()
                .setaddress("redis://" + properties.gethost() + ":" + properties.getport())
               .setpassword(properties.getpassword())
                .setconnectionpoolsize(properties.getpoolsize())
                .setconnectionminimumidlesize(properties.getminidlesize())
                .setidleconnectiontimeout(properties.getidletimeout())
                .setconnecttimeout(properties.getconnecttimeout())
                .setretryattempts(properties.getretryattempts())
                .setretryinterval(properties.getretryinterval())
                .setpingconnectioninterval(properties.getpinginterval())
                .setkeepalive(properties.iskeepalive())
        ;
        redissonclient redissonclient = redisson.create(config);
        // 注册消息发布订阅主题topic
        // 找到所有实现了redisson中messagelistener接口的bean名字
        string[] beannamesfortype = applicationcontext.getbeannamesfortype(messagelistener.class);
        for (string beanname : beannamesfortype) {
            // 通过bean名字获取到监听bean
            messagelistener bean = applicationcontext.getbean(beanname, messagelistener.class);
            class<? extends messagelistener> beanclass = bean.getclass();
            // 如果bean的注解里包含我们的自定义注解redistopic.class,则以redistopic注解的值作为name将该bean注册到bean工厂,方便在别处注入
            if (beanclass.isannotationpresent(redistopic.class)) {
                redistopic redistopic = beanclass.getannotation(redistopic.class);
                rtopic topic = redissonclient.gettopic(redistopic.topic());
                topic.addlistener(string.class, bean);
                configurablelistablebeanfactory beanfactory = applicationcontext.getbeanfactory();
                beanfactory.registersingleton(redistopic.topic(), topic);
            }
        }
        return redissonclient;
    }
}

在监听器上声明注解,如下服务即订阅了testredistopic02主题

@slf4j
@service
@redistopic(topic = "testredistopic02")
public class redistopiclistener02 implements messagelistener<string> {
    @override
    public void onmessage(charsequence channel, string msg) {
        log.info("02-监听消息(redis 发布/订阅): {}", msg);
    }
}

使用,发布消息

@slf4j
@repository
public class orderrepository implements iorderrepository {
    @resource(name = "testredistopic02")
    private rtopic testredistopic02;
    @resource(name = "testredistopic03")
    private rtopic testredistopic03;
    @override
    public string createorder(orderaggregate orderaggregate) {
        // 向  testredistopic02 发布消息
        testredistopic02.publish(json.tojsonstring(orderentity));
        // 向  testredistopic03 发布消息
        testredistopic03.publish(json.tojsonstring(orderentity));
        return orderid;
    }    
}    

到此这篇关于springboot中使用redisson + 自定义注解优雅的实现消息的发布订阅的文章就介绍到这了,更多相关springboot中使用redisson + 自定义注解优雅的实现消息的发布订阅内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com