3 Star 34 Fork 13

瑞文riven / smart-redisson-spring-boot-starter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

smart-redisson-spring-boot-starter

介绍

redisson的springboot starter简单实现,并基于spring-messaging对redisson的队列和延迟队列进行了封装,简洁方便的使用redisson的延迟队列
提供了发送队列消息的操作模板、基于注解的消费者实现

背景

日常开发中经常遇到延迟要求非常精准的场景,常规的通常没有延迟消息功能或者延迟不精准,
如rabbitmq,虽然可以通过死信队列处理模拟延迟队列,但是死信队列是阻塞的,
rocketmq,虽然有提供延迟消息的场景且消息不阻塞,但经过测试发现延迟时间不是非常精准,有时候误差在秒级。
经调研发现redisson基于redis实现了延迟队列,非则塞且误差在毫秒级,基于此场景,对其使用spring相关组件进行封装,以便在spring应用中方便的使用

运行环境及基础架构

java 1.8
spring 5.0.10
springboot 2.0.6

安装教程

1. 从1.1.4-beta.1开始已发布maven中央仓库,直接引用即可
<dependency>
   <groupId>io.gitee.the-best-riven</groupId>
   <artifactId>smart-redisson-spring-boot-starter</artifactId>
   <version>1.1.4-beta.1</version>
</dependency>
2. 1.1.4-beta.1之前的版本未发布maven中央仓库,需要手动引入相关依赖包
<dependency>
    <groupId>com.riven</groupId>
    <artifactId>smart-redisson-spring-boot-starter</artifactId>
    <version>1.0.0.RELEASE</version>
    <scope>system</scope>
    <systemPath>***</systemPath>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>5.0.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.11.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>
3. 有私服的可以将jar包放到私服,直接普通的引用即可
<dependency>
    <groupId>com.riven</groupId>
    <artifactId>smart-redisson-spring-boot-starter</artifactId>
    <version>1.1.3-beta.1</version>
</dependency>
4. 特别说明

1.1.4-beta.1之前的groupId为com.riven,因maven中央仓库的审核要求,
1.1.4-beta.1发布到maven中央仓库后groupId改为io.gitee.the-best-riven

使用说明

1. 引入starter之后,配置文件新增
spring:
  smart-redisson:
    #server-type: single
    #server-address: localhost:6379
    server-type: cluster
    server-address: localhost:7000,localhost:7001,localhost:7002
    password: 123456

不加配置默认Redis服务为单实例single、服务连接地址为localhost:6379。
配置结束之后即可使用通过spring容器使用RedissonClient了。

2. 如果需要使用队列,在spring容器注入一个RedissonQueue实例即可,如:
@Bean
public RedissonQueue redissonQueue() {
    return new RedissonQueue("riven", true, null, messageConverter());
}

创建队列的时候可以指定队列名称、是否延迟队列、隔离策略、消息转换器。
隔离策略主要是应用于如下场景:
在服务集群模式中,假设A、B、C三台机器,A机器生产的消息只希望自己消费,这就叫做隔离,
可通过指定隔离策略进行集群的隔离,源码提供了DefaultIsolationStrategy,可根据需要使用。
消息转换器主要是对消息进行转换以及一些附加处理如增加消息头等

3. 向队列发送消息
@Autowired
private RedissonTemplate redissonTemplate;

public void test() {
    CarLbsDto carLbsDto = new CarLbsDto();
    carLbsDto.setCid(1);
    carLbsDto.setBusinessType("0");
    carLbsDto.setCity("北京市");
    carLbsDto.setCityId(265);
    carLbsDto.setName("fsfds");
    carLbsDto.setCarNum("156156");
    redissonTemplate.sendWithDelay("riven", carLbsDto, 5000);
}
4. 消费消息

spring启动类开启@EnableRedisson,编写如下类即可

@Configuration
public class RedissonTestApplication {
    @Bean("myMessageConverter")
    public MessageConverter messageConverter() {
        return new MessageConverter() {
            @Override
            public QueueMessage<?> toMessage(Object object, Map<String, Object> headers) throws MessageConversionException {
                //do something you want, eg:
                headers.put("my_header", "my_header_value");
                return QueueMessageBuilder.withPayload(object).headers(headers).build();
            }

            @Override
            public Object fromMessage(RedissonMessage redissonMessage) throws MessageConversionException {
                byte[] payload = redissonMessage.getPayload();
                String payloadStr = new String(payload);
                return JSONObject.parseObject(payloadStr, CarLbsDto.class);
            }
        };
    }

    @RedissonListener(queues = "riven", messageConverter = "myMessageConverter")
    public void handler(@Header(value = RedissonHeaders.MESSAGE_ID, required = false) String messageId,
                        @Header(RedissonHeaders.DELIVERY_QUEUE_NAME) String queue,
                        @Header(RedissonHeaders.SEND_TIMESTAMP) long sendTimestamp,
                        @Header(RedissonHeaders.EXPECTED_DELAY_MILLIS) long expectedDelayMillis,
                        @Header(value = "my_header", required = false, defaultValue = "test") String myHeader,
                        @Payload CarLbsDto carLbsDto) {
        System.out.println(messageId);
        System.out.println(queue);
        System.out.println(myHeader);
        long actualDelay = System.currentTimeMillis() - (sendTimestamp + expectedDelayMillis);
        System.out.println("receive " + carLbsDto + ", delayed " + actualDelay + " millis");
    }
} 

其中注解可以配置消费的队列、异常处理器、隔离策略、消息转换器 其中隔离策略通常与生产者保持一致 异常处理器可自定义消费发生异常之后如何处理,源码提供了RequeueRedissonListenerErrorHandler,可根据需要使用 消息转换器是把RedissonMessage转换成需要的对象,当然不转换消费方法直接使用RedissonMessage作为参数也是可以的

设计说明/初衷

每个队列均可在定义时指定MessageConverter,如果不指定,则会使用RedissonTemplate中默认的全局MessageConverter。
每个消费者也可指定MessageConverter,如果不指定,则会尝试在spring容器中中寻找MessageConverter的bean实例,
还未找到,则使用默认的MessageConverter,默认的MessageConverter进行的操作是将从redis拿到的消息的消息体转换成字符串。
至于为什么是字符串呢?这还跟Redisson的序列化和反序列化有关。设计的初衷是,为了避免耦合、提升可扩展性,
序列化和反序列化使用的是fastjson(详见FastJsonCodec编码解码器),并且消息的内容不会包含任何项目或者类相关的信息。
试想一下,A项目发送消息com.a.TestClass对象到队列,如果是采用java的序列化,那么B项目消费消息的时候也必须严格按照
com.a.TestClass进行定义类,才能正确的接收到消息的内容,否则反序列化出错。同样json序列化带上类信息时,
也会存在同样的问题,这不是我们想要的。所以消息的存储完全是与项目、类信息等无关的,仅仅是一个json格式的数据,
所以消费者读到的数据实际上是一个json格式的字符串,在使用的时候我们要注意到,消费者接收到的消息都是基于json转换而来的,
如果我们不自定义MessageConverter转换器,那么我们拿到的数据消息体就是一个json字符串,消息头就是一个json对象。

常用类

1.常用的核心注解
EnableRedisson
RedissonListener
2.常用的核心类
RedissonClient
RedissonQueue
RedissonTemplate
RedissonMessage
3.常用的核心接口
IsolationStrategy
MessageConverter

性能测试

单线程写入速度1100/s左右,因为写入速度瓶颈明显不是在redis服务器上,所以测试客户端多线程写入,写入速度1.2w+/s。
消费速度1300/s左右。
以上测试数据为个人PC机测试结果,非专业测试机测试结果,仅供参考。

码云特技

  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. 码云官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解码云上的优秀开源项目
  4. GVP 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目
  5. 码云官方提供的使用手册 https://gitee.com/help
  6. 码云封面人物是一档用来展示码云会员风采的栏目 https://gitee.com/gitee-stars/
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

redisson的springboot starter实现,并基于spring-messaging对redisson的队列和延迟队列进行了实现。 展开 收起
Java
Apache-2.0
取消

发行版 (10)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/the-best-riven/smart-redisson-spring-boot-starter.git
git@gitee.com:the-best-riven/smart-redisson-spring-boot-starter.git
the-best-riven
smart-redisson-spring-boot-starter
smart-redisson-spring-boot-starter
master

搜索帮助