Spring Data Redis集成Redission

依赖引入

maven引入,这里基于Springboot2.3+,版本不用需要调整 redisson-spring-data-2x 依赖。

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--    redisson-->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.13.6</version>
        </dependency>
    </dependencies>

配置

这里使用application.yml配置,redission详细配置请参考:Redission配置参数说明

server:
  servlet:
    context-path: /
  port: 8888
spring:
  application:
    name: fk-boot
  redis:
    timeout: 1000 # 连接超时时间(毫秒)
    # redis集群
    cluster:
      nodes:
        - 10.2.55.107:6379
        - 10.2.55.107:6380
        - 10.2.55.107:6381
        - 10.2.55.107:6382
        - 10.2.55.107:6383
        - 10.2.55.107:6384

使用

  • Redis操作使用RedisTemplate注入即可。
  • Redission工具方法可以引入RedissionClient进行使用。

基本操作

        因为RedisTemplate会使用jdk序列化存储,所以一般使用StringRedisTemplate方法。

import com.lizz.RedisMoudle;
import com.lizz.exception.RedisException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @description: redis统一工具类
 * @author: lizz
 */
@Component
public class RedisTool {
    private static final Logger logger = LoggerFactory.getLogger(RedisTool.class);

    private final static String KEY_SPACER = ":";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 创建小写 redis key
     *
     * @param redisMoudle 业务模块名称
     * @param keys        业务功能key
     * @return value
     */
    public String createKey(RedisMoudle redisMoudle, String... keys) {
        StringBuilder keyBuffer = new StringBuilder();
        keyBuffer.append(redisMoudle.toString());
        for (String key : keys) {
            keyBuffer.append(KEY_SPACER);
            keyBuffer.append(key);
        }
        return keyBuffer.toString();
    }

    /**
     * 创建小写 redis key
     *
     * @param redisMoudle 业务模块名称
     * @param keys        业务功能key
     * @return key
     */
    public String createKey4Lower(RedisMoudle redisMoudle, String... keys) {
        StringBuilder keyBuffer = new StringBuilder();
        keyBuffer.append(redisMoudle.toString().toLowerCase());
        for (String key : keys) {
            keyBuffer.append(KEY_SPACER);
            keyBuffer.append(key.toLowerCase());
        }
        return keyBuffer.toString();
    }


    /**
     * 验证key的格式
     *
     * @param key key
     */
    private void checkKey(@NonNull String key) {
        if (!RedisMoudle.resolve(key.split(KEY_SPACER)[0])) {
            throw new RedisException("key mast use RedisMoudle");
        }
    }

    /**
     * 根据key值获取value
     *
     * @param key key in redis
     * @return value
     */
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 根据key值获取value
     *
     * @param key key in redis
     * @return value
     */
    public String get4Lower(String key) {
        return stringRedisTemplate.opsForValue().get(key.toLowerCase());
    }

    /**
     * key是否存在
     *
     * @param key key in redis
     * @return true:存在 false:不存在
     */
    public boolean hasKey(String key) {
        return stringRedisTemplate == null ? false : stringRedisTemplate.hasKey(key);
    }

    /**
     * key是否存在
     *
     * @param key key in redis
     * @return 存在 false:不存在
     */
    public boolean hasKey4Lower(String key) {
        return stringRedisTemplate == null ? false : stringRedisTemplate.hasKey(key.toLowerCase());
    }

    /**
     * 是否存在,存在重置过期时间
     *
     * @param key    key in redis
     * @param expire expire of key
     * @return true:key存在 false:key不存在
     */
    public boolean hasKey(String key, long expire) {
        if (hasKey(key)) {
            return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
        } else {
            return false;
        }
    }

    public boolean hasKey4Lower(String key, long expire) {
        if (hasKey(key)) {
            return stringRedisTemplate.expire(key.toLowerCase(), expire, TimeUnit.SECONDS);
        } else {
            return false;
        }
    }


    /**
     * 存储String数据
     *
     * @param key     主键
     * @param value   值
     * @param timeout 过期时间
     * @return
     */
    public boolean setex(String key, String value, long timeout) {
        try {
            checkKey(key);
            if (timeout > 0) {
                stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            } else {
                stringRedisTemplate.opsForValue().set(key, value);
            }
            return true;
        } catch (Exception e) {
            logger.error("RedisTool.setex error", e);
            return false;
        }
    }

    /**
     * 插入小写值
     * @param key 主键
     * @param value 值
     * @param timeout 过期时间
     * @return 插入是否成功
     */
    public boolean setex4Lower(String key, String value, long timeout) {
        try {
            checkKey(key);
            if (timeout > 0) {
                stringRedisTemplate.opsForValue().set(key.toLowerCase(), value, timeout, TimeUnit.SECONDS);
            } else {
                stringRedisTemplate.opsForValue().set(key.toLowerCase(), value);
            }
            return true;
        } catch (Exception e) {
            logger.error("RedisTool.setex  error", e);
            return false;
        }
    }

    /**
     * 存储String数据
     *
     * @param key   主键
     * @param value 值
     * @return true:插入成功, false:插入失败
     */
    public boolean set(String key, String value) {
        checkKey(key);
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     *
     * @param key 主键
     * @param value 值
     * @return 插入是否成功
     */
    public boolean set4Lower(String key, String value) {
        checkKey(key);
        try {
            stringRedisTemplate.opsForValue().set(key.toLowerCase(), value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

Spring Boot 集成 Redis Sentinel 模式主要是为了实现高可用的分布式 Redis 存储。Sentinel 是 Redis 官方提供的一个用于监控集群健康状态和选举主节点的工具。以下是集成 Spring Boot 和 Redis Sentinel 的一般步骤: 1. 添加依赖:在你的 Maven 或者 Gradle 项目中添加 Spring Data RedisSpring Cloud Config 的 Sentinel 版本依赖。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>sentinel-spring-boot-starter</artifactId> </dependency> // 或者 Gradle implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' implementation 'com.alibaba:sentinel-spring-boot-starter' ``` 2. 配置 Sentinel 信息:在 `application.properties` 或者 `application.yml` 中,添加 Sentinel 的地址、集群名、服务实例名等信息。 ```yaml spring.redis.sentinel.master=your-cluster-name spring.redis.sentinel.nodes=senode1:26379,senode2:26379,etc. spring.redis.sentinel.service-instance-name=your-service-instance-name ``` 3. 配置客户端:启用 Sentinel 配置,这会自动切换到 Sentinel 选择的主节点。 ```yaml spring.redis.sentinel.use-strict-hostname=true spring.redis.pool.max-active=8 ``` 4. 事务管理:如果需要支持 Redis 事务,记得启用 Spring Data Redis 的事务支持: ```yaml spring.redis.transaction.type=RETRY_ON_FAILURE ``` 5. Eureka 配置:如果你使用的是 Netflix Eureka 作为服务注册中心,确保它也配置了 Sentinel 集群地址。 6. 高级配置:可以根据实际需求调整连接池参数、超时时间等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lizz666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值