Redisson配置方式

简介:
Redisson** is a Redis Java client **with features of In-Memory Data Grid. It provides more convenient and easiest way to work with Redis. Redisson objects provides a separation of concern, which allows you to keep focus on the data modeling and application logic.
Redisson是一个Redis Java客户端,具有内存中数据网格的功能。它提供了使用Redis更方便、更简单的方法。Redisson对象提供了一种关注点分离,使您能够专注于数据建模和应用程序逻辑。
Based on high-performance async and lock-free Java Redis client and Netty framework.

总结一下springBoot项目中配置Redisson的方式:
首先,引入Redisson和启动器

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

除了配置文件,还可以用配置类的方式注入RedissonClient;但这里只总结用配置文件的方式。

各种配置优先级:
spring.redis.redisson.config > spring.redis.redisson.file > spring boot通用redis配置

使用spring boot通用redis配置

application.yml
(spring boot版本2.7.x)

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
#    password:
#    ssl:
#    timeout:
#    connectTimeout:
#    clientName:
#    cluster:
#      nodes:
#    sentinel:
#      master:
#      nodes:

(spring boot版本3.x,直接复制的官网的)

spring:
  data:
    redis:
      database: 
      host: 
      port: 
      password:
      ssl: 
      timeout:
      connectTimeout:
      clientName:
      cluster:
        nodes:
      sentinel:
        master:
        nodes:

注意:
通用配置中,配置的redis是单例,那么Redisson也是单例模式;
通用配置中,配置的redis是集群,那么Redisson也是集群模式;

使用redisson特有配置

方法一:直接写到spring boot的配置中

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
#    password:
#    ssl:
#    timeout:
#    connectTimeout:
#    clientName:
#    cluster:
#      nodes:
#    sentinel:
#      master:
#      nodes:
    redisson:
      config: |
        singleServerConfig:
          address: redis://192.168.1.10:6379
          database: 0
#          username: null
#          password: null

注意spring.redis.redisson.config后面那个 | 符号,丢失了redisson的特有配置就失效了,还是会使用上面的默认配置。

方法二:
使用单独的yml或者json配置文件(这里新增yml配置singleRedisson.yml)

singleServerConfig:
  address: redis://localhost123:6379
  database: 0
#  username: null
#  password: null

然后在spring boot配置文件application.yml中配置如下

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
#    password:
#    ssl:
#    timeout:
#    connectTimeout:
#    clientName:
#    cluster:
#      nodes:
#    sentinel:
#      master:
#      nodes:
    redisson:
      file: classpath:singleRedisson.yml

核心逻辑在Redisson自动化配置类中:

@Configuration
@ConditionalOnClass({Redisson.class, RedisOperations.class})
@AutoConfigureBefore({RedisAutoConfiguration.class})
@EnableConfigurationProperties({RedissonProperties.class, RedisProperties.class})
public class RedissonAutoConfiguration {
    private static final String REDIS_PROTOCOL_PREFIX = "redis://";
    private static final String REDISS_PROTOCOL_PREFIX = "rediss://";
	@ConditionalOnMissingBean({RedissonClient.class})
    public RedissonClient redisson() throws IOException {
        Method clusterMethod = ReflectionUtils.findMethod(RedisProperties.class, "getCluster");
        Method usernameMethod = ReflectionUtils.findMethod(RedisProperties.class, "getUsername");
        Method timeoutMethod = ReflectionUtils.findMethod(RedisProperties.class, "getTimeout");
        Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, this.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;
        }

        String username = null;
        if (usernameMethod != null) {
            username = (String)ReflectionUtils.invokeMethod(usernameMethod, this.redisProperties);
        }

        Config config;
        // 1.判断是否有spring.redis.redisson的config配置
        if (this.redissonProperties.getConfig() != null) {
            try {
                config = Config.fromYAML(this.redissonProperties.getConfig());
            } catch (IOException var15) {
                try {
                    config = Config.fromJSON(this.redissonProperties.getConfig());
                } catch (IOException var14) {
                    var14.addSuppressed(var15);
                    throw new IllegalArgumentException("Can't parse config", var14);
                }
            }
        // 2.判断是否有spring.redis.redisson的file配置
        } else if (this.redissonProperties.getFile() != null) {
            try {
                InputStream is = this.getConfigStream();
                config = Config.fromYAML(is);
            } catch (IOException var13) {
                try {
                    InputStream is = this.getConfigStream();
                    config = Config.fromJSON(is);
                } catch (IOException var12) {
                    var12.addSuppressed(var13);
                    throw new IllegalArgumentException("Can't parse config", var12);
                }
            }
        // 3.上面的都没有,判断是否有配置spring.redis.sentinel哨兵模式
        } else if (this.redisProperties.getSentinel() != null) {
            Method nodesMethod = ReflectionUtils.findMethod(Sentinel.class, "getNodes");
            Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, this.redisProperties.getSentinel());
            String[] nodes;
            if (nodesValue instanceof String) {
                nodes = this.convert(Arrays.asList(((String)nodesValue).split(",")));
            } else {
                nodes = this.convert((List)nodesValue);
            }

            config = new Config();
            ((SentinelServersConfig)((SentinelServersConfig)config.useSentinelServers().setMasterName(this.redisProperties.getSentinel().getMaster()).addSentinelAddress(nodes).setDatabase(this.redisProperties.getDatabase()).setConnectTimeout(timeout)).setUsername(username)).setPassword(this.redisProperties.getPassword());
        // 4.上面的都没有,就用spring boot redis通用配置
        } else {
            Method method;
            // 4.1 看是否是集群
            if (clusterMethod != null && ReflectionUtils.invokeMethod(clusterMethod, this.redisProperties) != null) {
                Object clusterObject = ReflectionUtils.invokeMethod(clusterMethod, this.redisProperties);
                method = ReflectionUtils.findMethod(clusterObject.getClass(), "getNodes");
                List<String> nodesObject = (List)ReflectionUtils.invokeMethod(method, clusterObject);
                String[] nodes = this.convert(nodesObject);
                config = new Config();
                ((ClusterServersConfig)((ClusterServersConfig)config.useClusterServers().addNodeAddress(nodes).setConnectTimeout(timeout)).setUsername(username)).setPassword(this.redisProperties.getPassword());
            } else {
                // 4.2 不是集群,配置为单例的
                config = new Config();
                String prefix = "redis://";
                method = ReflectionUtils.findMethod(RedisProperties.class, "isSsl");
                if (method != null && (Boolean)ReflectionUtils.invokeMethod(method, this.redisProperties)) {
                    prefix = "rediss://";
                }

                ((SingleServerConfig)((SingleServerConfig)config.useSingleServer().setAddress(prefix + this.redisProperties.getHost() + ":" + this.redisProperties.getPort()).setConnectTimeout(timeout)).setDatabase(this.redisProperties.getDatabase()).setUsername(username)).setPassword(this.redisProperties.getPassword());
            }
        }

        if (this.redissonAutoConfigurationCustomizers != null) {
            Iterator var22 = this.redissonAutoConfigurationCustomizers.iterator();

            while(var22.hasNext()) {
                RedissonAutoConfigurationCustomizer customizer = (RedissonAutoConfigurationCustomizer)var22.next();
                customizer.customize(config);
            }
        }

        return Redisson.create(config);
    }
}

然后,就可以在业务中通过spring容器,直接注入RedissonClient,使用Redisson了。

官网地址:
https://github.com/redisson/redisson/tree/master/redisson-spring-boot-starter

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Redisson配置方式可以通过创建一个RedissonConfig类来实现。在这个类中,你可以使用@Configuration注解来标记这是一个配置类,并使用@Bean注解来创建一个RedissonClient的bean。在这个bean的方法中,你可以使用Config.fromYAML或Config.fromJSON方法来读取配置文件,然后返回一个RedissonClient实例。例如,你可以使用以下代码来创建一个RedissonConfig类并配置Redisson: ``` @Configuration public class RedissonConfig { @Bean public RedissonClient redisson() throws IOException { Config config = Config.fromYAML(RedissonConfig.class.getClassLoader().getResource("redisson-config.yml")); return Redisson.create(config); } } ``` 在这个例子中,我们使用了YAML格式的配置文件(redisson-config.yml),你也可以使用JSON格式的配置文件(redisson-config.json)。在配置文件中,你可以设置各种Redisson的属性,比如连接地址、密码、集群模式等。另外,你还可以通过配置编码方式来实现Redisson的JSON序列化,将编码设置为org.redisson.codec.JsonJacksonCodec。如果你使用了RedisTemplate,你还需要增加相应的bean定义,并配置序列化/反序列化配置。 #### 引用[.reference_title] - *1* [Redis(十四)【Redisson分布式锁基础介绍】](https://blog.csdn.net/Wei_Naijia/article/details/129693379)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Springboot + redis操作多种实现(以及Jedis,Redisson,Lettuce的区别比较)](https://blog.csdn.net/qq_42105629/article/details/102589319)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [spring redisson 使用样例](https://blog.csdn.net/shengzi101/article/details/130782292)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值