首页 > 数据库 >lettuce+redisTemplate实现redis单击和集群的整合

lettuce+redisTemplate实现redis单击和集群的整合

时间:2023-06-19 23:13:22浏览次数:49  
标签:String 单击 redis springframework lettuce host org import

lettuce+redisTemplate实现redis单击和集群的整合

Springboot 整合redis是非常方便的,大致包含如下四部分

  • pom start相关jar的引入
  • properties/yaml 基础配置信息
  • config bean的init
  • bean的注入及使用

如果遇到网上的自动装配的实例直接跳过吧,哪怕再小的公司,密码也会加密处理,不可能自动装配。

1、pom

引入Springboot的redis相关组件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

2、properties基础配置

这里主要配置数据源,其他配置项没有,暂时简化了配置,一切使用默认

为了适配真实业务,这里采用的是双数据源配置,亦真亦假,一单节点一集群。

redis.biz.alone.host=39.105.198.245:6379
redis.biz.alone.auth=hcgk&2022
redis.biz.cluster.host=10.22.251.21:6379,10.22.251.28:6379,10.22.251.23:6379
redis.biz.cluster.auth=7ujm*IK<
lettuce.pool.max-total=12
# 最大活跃链接数 默认8(使用负值表示没有限制)
lettuce.pool.max-active=12
# 最大空闲连接数 默认8
lettuce.pool.max-idle=12
# 最小空闲连接数 默认0
lettuce.pool.min-idle=0
# 连接池最大阻塞等待时间(使用负值表示没有限制)
lettuce.pool.max-wait=-1

3、config

支持单击和集群

package com.wht.test.config;

import io.lettuce.core.ReadFrom;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

/**
 * 支持单机、集群和多实例
 *
 * @Author 红尘过客
 * @DateTime 2023-06-19 22:00:12
 */
@Configuration
public class LettuceRedisConfig {

    @Value("${redis.biz.alone.host}")
    private String bizAloneHost;

    @Value("${redis.biz.alone.auth}")
    private String bizAloneAuth;


    @Value("${redis.biz.cluster.host}")
    private String bizClusterHost;

    @Value("${redis.biz.cluster.auth}")
    private String bizClusterAuth;


    @Primary
    @Bean("bizAlone")
    public StringRedisTemplate bizAlone() {
        return getStringRedisTemplate(bizAloneHost, bizAloneAuth);
    }

//    @Primary
//    @Bean("bizCluster")
//    public StringRedisTemplate bizCluster() {
//        return getStringRedisTemplate(bizClusterHost, bizClusterAuth);
//    }

    /**
     * 封装单例配置
     *
     * @param host
     * @param password
     * @return
     */
    private RedisStandaloneConfiguration getRedisStandaloneConfiguration(String host, String password) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        String[] redisNode = host.split(":");
        if (redisNode.length == 2) {
            redisStandaloneConfiguration.setHostName(redisNode[0]);
            redisStandaloneConfiguration.setPort(Integer.parseInt(redisNode[1]));
        }
        if (password != null || password.trim().length() > 0) {
            redisStandaloneConfiguration.setPassword(password);
        }
        return redisStandaloneConfiguration;
    }

    /**
     * 把集群连接串拆分为redisNodes
     *
     * @param host
     * @return
     */
    private Set<RedisNode> getClusterNodes(String host) {
        String[] nodesArray = host.split(",");
        Set<RedisNode> clusterNodes = new HashSet<>();
        for (String node : nodesArray) {
            String[] redisNode = node.split(":");
            clusterNodes.add(new RedisNode(redisNode[0], Integer.parseInt(redisNode[1])));
        }
        return clusterNodes;
    }

    /**
     * 封装集群配置
     *
     * @param host
     * @param password
     * @return
     */
    private RedisClusterConfiguration getRedisClusterConfiguration(String host, String password) {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        redisClusterConfiguration.setClusterNodes(getClusterNodes(host));
        if (password != null || password.trim().length() > 0) {
            redisClusterConfiguration.setPassword(password);
        }
        return redisClusterConfiguration;
    }

    /**
     * 创建alone bean
     * 这里用LettucePoolingClientConfiguration 预留了连接池
     *
     * @param host
     * @param password
     * @return
     */
    private StringRedisTemplate getStringRedisTemplate(String host, String password) {
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
//        builder.poolConfig(pool)
        LettuceConnectionFactory connectionFactory = null;
        // 集群要做拓扑刷新,应对准备切换,摸个节点挂掉等问题
        if (host.contains(",")) {
            ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                    .enablePeriodicRefresh(Duration.ofSeconds(10))
                    .enableAllAdaptiveRefreshTriggers()
                    .build();
            ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                    .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(60)))
                    .topologyRefreshOptions(topologyRefreshOptions)
                    .build();

            LettuceClientConfiguration clientConfiguration = builder.commandTimeout(Duration.ofSeconds(60))
                    .readFrom(ReadFrom.REPLICA_PREFERRED)
                    .clientOptions(clusterClientOptions)
                    .build();
            connectionFactory = new LettuceConnectionFactory(getRedisClusterConfiguration(host, password), clientConfiguration);
        } else {
            connectionFactory = new LettuceConnectionFactory(getRedisStandaloneConfiguration(host, password), builder.build());
        }
        connectionFactory.afterPropertiesSet();
        return getStringRedisTemplate(connectionFactory);
    }

    private StringRedisTemplate getStringRedisTemplate(LettuceConnectionFactory connectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        return stringRedisTemplate;
    }
}

4、使用

这里简单搞个schedule任务

package com.wht.test.schedule;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * desc
 *
 * @Author 红尘过客
 * @DateTime 2023-06-15 10:15:35
 */
@Component
public class RedisTestJob {
    @Resource(name = "bizAlone")
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "* * * * * * ")
    public void test() {
        for (int i = 0; i < 100; i++) {
            String key = "test_" + i;
            stringRedisTemplate.opsForValue().set(key, "test_value_" + i, Duration.ofHours(1));
            String name = (String) stringRedisTemplate.opsForValue().get(key);
            System.out.println("value = " + name);
        }


    }
}

可以正常写入数据到redis了

标签:String,单击,redis,springframework,lettuce,host,org,import
From: https://www.cnblogs.com/hcgk/p/17492457.html

相关文章

  • Windows环境下Redis的安装以及Redis Desktop Manager的下载安装
    ————本文介绍了Windows环境下Redis的安装,以及Redis数据库管理工具RedisDesktopManager的下载和安装目录|一、Windows环境下安装Redis||--|--||二、RedisDesktopManager的下载及安装|一、Windows环境下安装Redis下载地址:https://github.com/tporadowski/redis/......
  • 2023-06-19:讲一讲Redis分布式锁的实现?
    2023-06-19:讲一讲Redis分布式锁的实现?答案2023-06-19:Redis分布式锁最简单的实现要实现分布式锁,确实需要使用具备互斥性的Redis操作。其中一种常用的方式是使用SETNX命令,该命令表示"SETifNotExists",即只有在key不存在时才设置其值,否则不进行任何操作。通过这种方式,两个客户端......
  • 2023-06-19:讲一讲Redis分布式锁的实现?
    2023-06-19:讲一讲Redis分布式锁的实现?答案2023-06-19:Redis分布式锁最简单的实现要实现分布式锁,确实需要使用具备互斥性的Redis操作。其中一种常用的方式是使用SETNX命令,该命令表示"SETifNotExists",即只有在key不存在时才设置其值,否则不进行任何操作。通过这种方式,两个客户端进程......
  • 基于Redis实现分布式锁
    问题描述服务A和服务B都需要访问共享资源C。这时就会发生共服务A和服务B都去抢占享资源C,为了避免这种抢占,就需要引入分布式锁。分布式锁介绍分布式锁:控制分布式系统有序的去对共享资源进行操作,通过互斥来保证数据的一致性。解决方案基于redis实现分布式锁可以使用reids中的......
  • Redis和Sentinel的安装部署和配置
    为了提升数据检索的效率,有时候我们会在数据库前加一层缓存,Redis就是常见的一种缓存组件,他的全称是REmoteDIctionaryServer,是一个由SalvatoreSanfilippo写的key-value存储系统,而且是可以跨平台的非关系型数据库。Redis是一个开源的使用ANSIC语言编写、遵守BSD协议、支持网络、可......
  • redis基础笔记
    redis1、redis的基本使用学习网址http://redisdoc.com/说明:redis安装好后,有16个数据库,初始默认使用0号库,编号是0...151、添加key-val[set]2、查看当i去哪redis的所有key[keys*]获取key对应的值[getkey]切换redis数据库[seletionindex]如何查看当前数据库的key-va......
  • 安装redis
    Redis是一个开源的高性能键值对存储系统,它支持多种数据结构,包括字符串、哈希表、列表、集合和有序集合。Redis的出色性能和灵活性使其成为许多应用程序的首选数据存储解决方案。在本篇博客中,我们将介绍如何在Linux系统上安装Redis。1.安装依赖项在安装Redis之前,我们需要安装一......
  • 《面试1v1》Redis持久化
    《面试1v1》连载中...面试官:Redis是内存数据库,数据存放在内存中,当Redis服务重启数据会丢失,那么Redis如何保证数据的持久化?候选人:Redis提供两种持久化方案:RDB(RedisDataBase)和AOF(AppendOnlyFile)。面试官:说说RDB吧,它的工作原理是什么?候选人:RDB的工作原理很简单,就......
  • Redis - 数据结构类型及使用场景详解
    一.简介Redis是由SalvatoreSanfilippo编写的一个key-value存储系统,是跨平台的非关系型数据库。Redis是一个开源的,使用C语言编写的,遵守BSD协议,支持网络,可基于内存,分布式,可选持久性的键值对(key-value)存储数据库,并且提供了多种语言的API。二.特性1.基于内存存储(不开启持久化的......
  • Redisson分布式锁和同步器详解-官方原版
    一、锁定基于Redis的Java分布式可重入锁对象,并实现了锁接口。如果获取锁的Redisson实例崩溃,则此类锁可能会在获取状态下永久挂起。为了避免这种Redisson维护锁watchdog,当锁持有者Redisson实例处于活动状态时,它会延长锁的到期时间。默认情况下,lockwatchdog超时为30秒,可以通过Config......