SpringBoot系列之集成Redission入门与实践教程

Redisson是一款基于java开发的开源项目,提供了很多企业级实践,比如分布式锁、消息队列、异步执行等功能。本文基于Springboot2版本集成redisson-spring-boot-starter实现redisson的基本应用

软件环境:

  • JDK 1.8

  • SpringBoot 2.2.1

  • Maven 3.2+

  • Mysql 8.0.26

  • redisson-spring-boot-starter 3.15.6

  • 开发工具

    • IntelliJ IDEA

    • smartGit


项目搭建:

快速新建一个Spring Initializr项目,service url就选择这个https://start.aliyun.com,spring官网的url

在这里插入图片描述

选择jdk的版本,maven类型的项目

在这里插入图片描述

选择需要的依赖,选择之后,新生成的项目就会自动加上需要的maven配置,点击next生成一个SpringBoot的项目,不需要自己手工进行配置maven

在这里插入图片描述

这个里面没集成Redisson的starter,所以需要手工进行配置,需要注意一下redisson-spring-boot-starterSpringBoot对应的版本关系

在这里插入图片描述

pom.xml文件加上redisson-spring-boot-starter配置,然后reimport引入jar

 <dependency>
     <groupId>org.redisson</groupId>
     <artifactId>redisson-spring-boot-starter</artifactId>
     <version>3.15.6</version>
</dependency>

对于Redisson的配置,有多种方式,可以使用json文件配置,也可以使用yaml文件配置,然后再引进来,如下,新建一个redisson.yml文件,加上单机版的配置

redisson.yml

singleServerConfig:
  idleConnectionTimeout: 10000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  address: "redis://127.0.0.1:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 32
  connectionPoolSize: 64
  database: 0
  dnsMonitoringInterval: 5000
threads: 8
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
"transportMode":"NIO"

application.yml里引进redisson.yml

spring:
  redis:
    redisson:
      file: classpath:redisson.yml

另外一种方式是可以直接在application.yml里直接加上配置,这种方式可能对于使用了分布式配置中心管理的项目更加方便一些

spring:
  redis:
    redisson:
      config: |
        singleServerConfig:
          idleConnectionTimeout: 10000
          connectTimeout: 10000
          timeout: 3000
          retryAttempts: 3
          retryInterval: 1500
          password: null
          subscriptionsPerConnection: 5
          clientName: null
          address: "redis://127.0.0.1:6379"
          subscriptionConnectionMinimumIdleSize: 1
          subscriptionConnectionPoolSize: 50
          connectionMinimumIdleSize: 32
          connectionPoolSize: 64
          database: 0
          dnsMonitoringInterval: 5000
        threads: 0
        nettyThreads: 0
        codec: !<org.redisson.codec.JsonJacksonCodec> {}
        transportMode: "NIO"

在项目中如果想要自己加上配置,创建一个redisson可以先创建一个Config对象,如何进行设置就可以

Config config = new Config();
config.useSingleServer().setAddress("redis://192.168.8.12
8:6379");
config.setCodec(new StringCodec());
return Redisson.create(config);

翻看redisson-spring-boot-starter的源码,也是创建Config,进行设置,这个starter为我们提供了自动配置功能,源码路径:org.redisson.spring.starter.RedissonAutoConfiguration#redisson

 public RedissonClient redisson() throws IOException {
        Config config = null;
        Method clusterMethod = ReflectionUtils.findMethod(RedisProperties.class, "getCluster");
        Method timeoutMethod = ReflectionUtils.findMethod(RedisProperties.class, "getTimeout");
        Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, redisProperties);
        int timeout;
        if(null == timeoutValue){
            timeout = 10000;
        }else if (!(timeoutValue instanceof Integer)) {
            Method millisMethod = ReflectionUtils.findMethod(timeoutValue.getClass(), "toMillis");
            timeout = ((Long) ReflectionUtils.invokeMethod(millisMethod, timeoutValue)).intValue();
        } else {
            timeout = (Integer)timeoutValue;
        }

        if (redissonProperties.getConfig() != null) {
            try {
                config = Config.fromYAML(redissonProperties.getConfig());
            } catch (IOException e) {
                try {
                    config = Config.fromJSON(redissonProperties.getConfig());
                } catch (IOException e1) {
                    throw new IllegalArgumentException("Can't parse config", e1);
                }
            }
        } else if (redissonProperties.getFile() != null) {
            try {
                InputStream is = getConfigStream();
                config = Config.fromYAML(is);
            } catch (IOException e) {
                // trying next format
                try {
                    InputStream is = getConfigStream();
                    config = Config.fromJSON(is);
                } catch (IOException e1) {
                    throw new IllegalArgumentException("Can't parse config", e1);
                }
            }
        } else if (redisProperties.getSentinel() != null) {
            Method nodesMethod = ReflectionUtils.findMethod(Sentinel.class, "getNodes");
            Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, redisProperties.getSentinel());

            String[] nodes;
            if (nodesValue instanceof String) {
                nodes = convert(Arrays.asList(((String)nodesValue).split(",")));
            } else {
                nodes = convert((List<String>)nodesValue);
            }

            config = new Config();
            config.useSentinelServers()
                .setMasterName(redisProperties.getSentinel().getMaster())
                .addSentinelAddress(nodes)
                .setDatabase(redisProperties.getDatabase())
                .setConnectTimeout(timeout)
                .setPassword(redisProperties.getPassword());
        } else if (clusterMethod != null && ReflectionUtils.invokeMethod(clusterMethod, redisProperties) != null) {
            Object clusterObject = ReflectionUtils.invokeMethod(clusterMethod, redisProperties);
            Method nodesMethod = ReflectionUtils.findMethod(clusterObject.getClass(), "getNodes");
            List<String> nodesObject = (List) ReflectionUtils.invokeMethod(nodesMethod, clusterObject);

            String[] nodes = convert(nodesObject);

            config = new Config();
            config.useClusterServers()
                .addNodeAddress(nodes)
                .setConnectTimeout(timeout)
                .setPassword(redisProperties.getPassword());
        } else {
            config = new Config();
            String prefix = REDIS_PROTOCOL_PREFIX;
            Method method = ReflectionUtils.findMethod(RedisProperties.class, "isSsl");
            if (method != null && (Boolean)ReflectionUtils.invokeMethod(method, redisProperties)) {
                prefix = REDISS_PROTOCOL_PREFIX;
            }

            config.useSingleServer()
                .setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setConnectTimeout(timeout)
                .setDatabase(redisProperties.getDatabase())
                .setPassword(redisProperties.getPassword());
        }
        if (redissonAutoConfigurationCustomizers != null) {
            for (RedissonAutoConfigurationCustomizer customizer : redissonAutoConfigurationCustomizers) {
                customizer.customize(config);
            }
        }
        return Redisson.create(config);
    }

在项目中使用的话,一般直接用@Resource加一个RedissonClient即可,不需要自己创建了,下面给出使用Redisson API实现的共同关注的人和排名榜的简单例子

package com.example.redission;

import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
import org.redisson.api.*;
import org.redisson.client.RedisClient;
import org.redisson.client.protocol.ScoredEntry;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;

@SpringBootTest
class SpringbootRedissionApplicationTests {

    @Resource
    private RedissonClient redissonClient;

    @Test
    void contextLoads() throws ExecutionException, InterruptedException {
        // 共同关注的人
        RSet<Object> tom = redissonClient.getSet("tom");
        tom.addAll(Lists.newArrayList("令狐冲","james","风清扬"));
        RSet<Object> jack = redissonClient.getSet("jack");
        jack.addAll(Lists.newArrayList("令狐冲","tim","jack"));
        System.out.println("共同关注的人:"+tom.readIntersectionAsync("jack").get());


        // 排名榜
        RScoredSortedSet<String> school = redissonClient.getScoredSortedSet("school");
        school.add(60, "tom");
        school.add(60, "jack");
        school.add(60, "tim");
        school.addScore("tom", 20);
        school.addScore("jack", 10);
        school.addScore("tim", 30);
        RFuture<Collection<ScoredEntry<String>>> collectionRFuture = school.entryRangeReversedAsync(0, -1);
        Iterator<ScoredEntry<String>> iterator = collectionRFuture.get().iterator();
        System.out.println("成绩从高到低排序");
        while(iterator.hasNext()) {
            ScoredEntry<String> next = iterator.next();
            String value = next.getValue();
            System.out.println(value);
        }
        RFuture<Collection<ScoredEntry<String>>> collectionRFuture1 = school.entryRangeReversedAsync(0, 2);
        Iterator<ScoredEntry<String>> iterator1 = collectionRFuture1.get().iterator();
        System.out.println("成绩前三名");
        while (iterator1.hasNext()) {
            System.out.println(iterator1.next().getValue());
        }

    }

}

附录

官网的Readme文档:https://github.com/redisson/redisson/blob/master/redisson-spring-boot-starter/README.md

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/120885.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【算法-链表2】反转链表 和 两两交换链表节点

今天&#xff0c;带来链表相关算法的讲解。文中不足错漏之处望请斧正&#xff01; 理论基础点这里 反转链表 1. 思路 链表操作的本质是修改连接关系&#xff0c;本题我们需要反转链表&#xff0c;也就是每次都让当前节点的next指向自己的上一个。而题目给的是单链表&#xf…

【React-Native开发3D应用】React Native加载GLB格式3D模型并打包至Android手机端

【React-Native开发3D应用】React Native加载GLB格式3D模型并打包至Android手机端 【加载3D模型】**React Native上如何加载glb格式的模型**第零步&#xff0c;选择相关模型第一步&#xff0c;导入相关模型加载库第二步&#xff0c;自定义GLB模型加载钩子第三步&#xff0c;借助…

Modbus通讯模拟仿真环境的搭建

文章目录 一、概要二、所需工具介绍三、搭建虚拟仿真环境1.Modbus RTU虚拟仿真环境搭建1.1.虚拟串口工具&#xff08;VSPD&#xff09;使用1.2.虚拟从站工具&#xff08;ModSim32&#xff09;使用1.3.虚拟主站工具&#xff08;Modscan32&#xff09;使用1.4.更改虚拟从站工具&a…

【算法】第二代遗传算法NSGA-II优化SVR超参数模型

NSGA-II介绍 NSGA-II&#xff08;Non-dominated Sorting Genetic Algorithm II&#xff09;是一种多目标优化算法&#xff0c;用于解决具有多个冲突目标的优化问题。它通过模拟进化过程中的自然选择和遗传操作&#xff0c;逐步改进种群中的解&#xff0c;以找到一组尽可能好的解…

Halcon的 Filter (过滤)目录之add_Image算子

Halcon两个图像相加可以应用在图像融合的场景中。通过将两幅图像的亮度信息相加&#xff0c;可以生成一幅新的图像&#xff0c;使得图像的细节更加清晰&#xff0c;提高目标检测和识别的准确率。例如&#xff0c;在红外图像和可见光图像融合中&#xff0c;加法运算可以将两幅图…

Linux程序设计shell程序学习

目录 1、编写shell脚本&#xff0c;通过循环的形式在终端上打印出等腰梯形 2、编写一个bash脚本程序&#xff0c;用for循环实现将当前目录下的所有.c文件移到指定的目录下&#xff0c;最后在显示器上显示指定目录下的文件和目录。 3、自行编写 shell 脚本&#xff0c;实现从…

【JAVA学习笔记】66 - 本章作业(IO流)

项目代码 https://github.com/yinhai1114/Java_Learning_Code/tree/main/IDEA_Chapter19/src/com/yinhai/homework 1.使用File类和FileWriter类 (1)在判断e盘下是否有文件夹mytemp&#xff0c;如果没有就创建mytemp public class Homework01 {public static void main(String…

小程序游戏对接广告收益微信小游戏抖音游戏软件

小程序游戏对接广告是一种常见的游戏开发模式&#xff0c;开发者可以通过在游戏中嵌入广告来获取收益。以下是一些与小程序游戏对接广告收益相关的关键信息&#xff1a; 小程序游戏广告平台选择&#xff1a; 选择适合你的小程序游戏的广告平台非常重要。不同的平台提供不同类型…

塔望食研院|骆驼奶市场规模庞大,百亿体量,品牌升级!

自2022年12月塔望咨询开设塔望食品大健康行业与消费研究院&#xff08;简称塔望食研院&#xff09;栏目以来&#xff0c;塔望食研院以“为食品行业品牌高质量发展赋能”为理念&#xff0c;不断发布食品大健康行业研究、消费研究报告。塔望食研院致力于结合消费调研数据、企业数…

智能井盖传感器功能,万宾科技产品介绍

在国家治理方面&#xff0c;对社会的治理是一个重要的领域&#xff0c;一定要在推进社会治理现代化过程中提高市政府的管理和工作能力&#xff0c;推动社会拥有稳定有序的发展。在管理过程中对全市井盖进行统一化管理&#xff0c;可能是市政府比较头疼的难题&#xff0c;如果想…

SpringBoot进制转换规则问题

1.填写yml文件 dataSource:driver-class-name: com.mysql.jdbc.Driver789password: 01272.测试类 package com.forever;import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.Spri…

kubernetes-调度

目录 一、k8s调度简介 二、影响kubernetes调度的因素 1、nodename 2、nodeselector 3、亲和与反亲和 &#xff08;1&#xff09;nodeaffinity &#xff08;2&#xff09;podaffinity&#xff08;亲和&#xff09; &#xff08;3&#xff09;podantiaffinity&#xff0…

AI系统源码ChatGPT网站源码+ai绘画系统/支持GPT4.0/支持Midjourney局部编辑重绘

一、AI创作系统 SparkAi创作系统是基于OpenAI很火的ChatGPT进行开发的Ai智能问答系统和Midjourney绘画系统&#xff0c;支持OpenAI-GPT全模型国内AI全模型。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。那么如…

Python异步编程入门

文章目录 异步编程概念asyncio模块基础event loop和coroutineasync与await关键字代码示例结论在现代软件开发中,异步编程已经成为一个不可或缺的概念,尤其是在处理I/O密集型任务和高并发需求时。Python作为一门多范式编程语言,自3.5版本以来,通过引入asyncio模块和async/aw…

SPASS-图表的创建编辑

点击折线图 展示图如下&#xff1a; 双击图表&#xff0c;可进行编辑 图表基本设定 选择、移动图表元素和调整图表元素的大小 鼠标点击图表元素选择Tab键进行轮换选择Ctrl键鼠标进行多个元素选择十字箭头——移动元素双头箭头——调整元素大小 更改图表的外观 文本的内容、…

番外篇:Linux中好玩的指令(Ubuntu环境)

前言 我知道&#xff0c;Linux的学习总是枯燥乏味的&#xff0c;今天给大家带来一些好玩的指令&#xff0c;供大家娱乐开心&#xff0c;整理不易&#xff0c;希望大家能够多多支持一下。 1. lolcat指令 输入以下命令即可安装lolcat&#xff1a; sudo apt-get install lolcat 安…

洛谷 P1020 [NOIP1999 普及组] 导弹拦截【一题掌握三种方法:动态规划+贪心+二分】最长上升子序列LIS解法详解

P1020 [NOIP1999 普及组] 导弹拦截 前言题目题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 提示题目分析注意事项 代码动态规划&#xff08;NOIP要求&#xff1a;时间复杂度O(n^2^)&#xff09;贪心二分&#xff08;O(nlgn)&#xff09; 后话额外测试用例样例输入 #1…

微服务-grpc

微服务 一、微服务&#xff08;microservices&#xff09; 近几年,微服这个词闯入了我们的视线范围。在百度与谷歌中随便搜一搜也有几千万条的结果。那么&#xff0c;什么是微服务 呢&#xff1f;微服务的概念是怎么产生的呢&#xff1f; 我们就来了解一下Go语言与微服务的千丝…

Java设计模式之迭代器模式

定义 提供一个对象来顺序访问聚合对象中的一系列数据&#xff0c;而不暴露聚合对象的内部表示。 结构 迭代器模式主要包含以下角色&#xff1a; 抽象聚合角色&#xff1a;定义存储、添加、删除聚合元素以及创建迭代器对象的接口。具体聚合角色&#xff1a;实现抽象聚合类&a…

电机控制::理论分析::延迟环节对系统的影响

控制工程与理论 - 知乎 (zhihu.com) 浅论控制器的增益大小 (上) - 知乎 (zhihu.com) 浅论控制器的增益大小 (下) - 知乎 (zhihu.com) 延迟环节对控制系统的影响_延时环节的传递函数-CSDN博客
最新文章