SpringBoot3整合Redis

添加Maven坐标

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.57</version>
        </dependency>
        <!-- Lettuce连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

添加yaml配置

spring:
  data:
    redis:
      # 基础连接配置
      database: 0             # 使用的数据库索引(0-15)
      host: 172.18.208.1        # Redis服务器地址
      port: 6379              # Redis服务器端口
      password: 666666        # Redis密码
      timeout: 3000ms         # 连接超时时间(毫秒)
      connect-timeout: 3000ms # 连接建立超时时间(毫秒)
      # Lettuce客户端配置
      lettuce:
        # 连接池配置
        pool:
          max-active: 8     # 最大活跃连接数
          max-idle: 9       # 最大空闲连接数
          min-idle: 0       # 最小空闲连接数
          max-wait: -1ms    # 最大等待时间(-1表示无限制)
          # 连接池行为配置
          time-between-eviction-runs: 30s  # 空闲连接回收间隔时间

RedisConfig.java

package org.example.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * ClassName: RedisConfig
 * Package: com.calo.config
 * Description:
 *
 * @Author wangxuezheng
 * @Create 2024/2/26 14:11
 * @Version 1.0
 */
@Configuration
public class RedisConfig {

    /**
     * redis序列化的工具配置类,下面这个请一定开启配置
     *
     * 127.0.0.1:6379> keys *
     *
     * 1) "ord:102"  序列化过
     * 2) "\xac\xed\x00\x05t\x00\aord:102"   野生,没有序列化过
     * this.redisTemplate.opsForValue(); //提供了操作string类型的所有方法
     * this.redisTemplate.opsForList(); // 提供了操作list类型的所有方法
     * this.redisTemplate.opsForSet(); //提供了操作set的所有方法
     * this.redisTemplate.opsForHash(); //提供了操作hash表的所有方法
     * this.redisTemplate.opsForZSet(); //提供了操作zset的所有方法
     *
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory)
    {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //设置key序列化方式string
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}

RedisClient.java

package org.example.redis;

import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: RedisClient
 * Description:
 *
 * @Author wangxuezheng
 * @Create 2024/3/1 18:54
 * @Version 1.0
 */
@Component
public class RedisClient {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Redis SET 命令 - 设置指定 key 的值
     *
     * 如果 key 已经存储其他值, SET 就覆写旧值,且无视类型。
     *
     * @param key 键 不能为空
     * @param value 值 不能为空
     * @return true - 成功
     *         false - 失败
     */
    public Boolean setKV(String key, Object value) {

        if (key == null || "".equals(key)
                || value == null || "".equals(value)) {
            return false;
        }

        try {
            redisTemplate.opsForValue().set(key, value);
        }catch (Exception e) {
            throw e;
        }

        return true;
    }

    /**
     *  Redis Setex 命令为指定的 key 设置值及其过期时间。
     *  如果 key 已经存在, SETEX 命令将会替换旧的值。
     *
     * @param key 键
     * @param value 值
     * @param seconds 时长 单位: 秒
     * @return true - 成功
     *             false - 失败
     */
    public Boolean setKVWithTime(String key, Object value, long seconds) {

        if (key == null || "".equals(key)
                || value == null || "".equals(value)
                || seconds <= 0) {
            return false;
        }

        try {
            redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        }catch (Exception e) {
            throw e;
        }

        return true;
    }

    /**
     * Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 null
     * 使用时需要判断返回值是否为 null
     *
     * @param key 键
     * @return Object
     */
    public Object getKV(String key) {

        if (key == null || "".equals(key)) {
            return null;
        }

        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 null
     * 使用时需要判断返回值是否为 null
     *
     * @param key 键
     * @param objectType 转换的类型.class
     * @return T
     * @param <T> 类型.class
     */
    public <T> T getKVForType(String key, Class<T> objectType) {

        if (key == null || "".equals(key)) {
            return null;
        }

        try {
            Object object = redisTemplate.opsForValue().get(key);
            if (object == null) {
                return null;
            }
            return JSONObject.parseObject(JSONObject.toJSONString(object), objectType);
        }catch (Exception e) {
            throw e;
        }
    }

    /**
     * Redis Hset 命令用于为哈希表中的字段赋值 。
     * 如果哈希表不存在,一个新的哈希表被创建并进行 HSET 操作。
     * 如果字段已经存在于哈希表中,旧值将被覆盖。
     *
     * @param key 键
     * @param field 字段
     * @param value 值
     * @return
     *          true - 成功
     *          false - 失败
     */
    public Boolean setHash(String key, Object field, Object value) {

        if (key == null || "".equals(key)
                || field == null || "".equals(field)
                || value == null || "".equals(value)) {
            return false;
        }

        try {
            redisTemplate.opsForHash().put(key, field, value);
        } catch (Exception e) {
            throw e;
        }

        return true;
    }

    /**
     * Redis Hset 命令用于为哈希表中的字段赋值 。并设置过期时长
     * 如果哈希表不存在,一个新的哈希表被创建并进行 HSET 操作。
     * 如果字段已经存在于哈希表中,旧值将被覆盖。
     *
     * @param key 键
     * @param field 字段
     * @param value 值
     * @param seconds 时长 单位: 秒
     * @return
     */
    public Boolean setHashWithTime(String key, Object field, Object value, long seconds) {

        if (key == null || "".equals(key)
                || field == null || "".equals(field)
                || value == null || "".equals(value)
                || seconds <= 0) {
            return false;
        }

        try {
            this.setHash(key, field, value);
            this.expire(key, seconds);
        } catch (Exception e) {
            throw e;
        }

        return true;
    }
    /**
     * Redis Hget 命令用于返回哈希表中指定字段的值。
     *
     * 返回给定字段的值。如果给定的字段或 key 不存在时,返回 null
     *
     * @param key 键
     * @param field 字段
     * @return 返回Object 或 null
     */
    public Object getHash(String key, Object field) {

        if (key == null || "".equals(key)
                || field == null || "".equals(field)) {
            return null;
        }

        try {
            return redisTemplate.opsForHash().get(key, field);
        } catch (Exception e) {
            throw e;
        }

    }

    /**
     * Redis Hget 命令用于返回哈希表中指定字段的值。
     * 返回给定字段的值。如果给定的字段或 key 不存在时,返回 null
     *
     * @param key 键
     * @param field 字段
     * @param objectType 类型.class
     * @return 返回具体类型 或 null
     * @param <T>
     */
    public <T> T getHashForType(String key, Object field, Class<T> objectType) {

        if (key == null || "".equals(key)
                || field == null || "".equals(field)) {
            return null;
        }

        try {

            Object object = this.getHash(key, field);
            if (object == null) {
                return null;
            }

            return JSONObject.parseObject(JSONObject.toJSONString(object), objectType);

        } catch (Exception e) {
            throw e;
        }

    }

    /**
     * Redis Hmset 命令用于同时将多个 field-value (字段-值)对设置到哈希表中。
     * 此命令会覆盖哈希表中已存在的字段。
     * 如果哈希表不存在,会创建一个空哈希表,并执行 HMSET 操作。
     *
     * @param key 值
     * @param map map集合
     * @return true - 成功
     *          false - 失败
     */
    public Boolean setHashMap(String key, Map<Object, Object> map) {

        if (key == null || "".equals(key)
                || map == null || map.size() <= 0) {
            return false;
        }

        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            throw e;
        }

        return true;
    }

    /**
     *
     * Redis Hmset 命令用于同时将多个 field-value (字段-值)对设置到哈希表中。
     * 此命令会覆盖哈希表中已存在的字段。
     * 如果哈希表不存在,会创建一个空哈希表,并执行 HMSET 操作。
     *
     * @param key 值
     * @param map map集合
     * @param seconds 时长 单位: 秒
     * @return true - 成功
     *          false - 失败
     */
    public Boolean setHashMapWithTime(String key, Map<Object, Object> map, long seconds) {

        if (key == null || "".equals(key)
                || map == null || map.size() <= 0
                || seconds <= 0) {
            return false;
        }

        try {
            this.setHashMap(key, map);
            this.expire(key, seconds);
        } catch (Exception e) {
            throw e;
        }
        return true;
    }

    /**
     * Redis Hgetall 命令用于返回哈希表中,所有的字段和值。
     *
     *  若 key 不存在,返回空列表。
     *
     * @param key 键
     * @return Map集合 或 null
     */
    public Map<Object, Object> getHashMapAll(String key) {

        if (key == null || "".equals(key)) {
            return null;
        }

        try {
            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * Redis Hdel 命令用于删除哈希表 key 中的一个指定字段,不存在的字段将被忽略。
     *
     * @param key 键
     * @param field 字段
     * @return true - 成功
     *          false - 失败
     */
    public Boolean delHashOne(String key, Object field) {

        if (key == null || "".equals(key) || field == null) {
            return false;
        }

        try {
            return redisTemplate.opsForHash().delete(key, field) > 0;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * Redis Hdel 命令用于删除哈希表 key 中的一个或多个指定字段,不存在的字段将被忽略。
     *
     * @param key 键
     * @param fields 数组
     * @return true - 成功
     *          false - 失败
     */
    public Boolean delHashMore(String key, Object[] fields) {

        if (key == null || "".equals(key)
                || fields == null || fields.length <= 0) {
            return false;
        }

        try {
            return redisTemplate.opsForHash().delete(key, fields) > 0;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     *
     * (List) 将一个或多个值插入到列表(最左边或者最右边)
     *
     * @param side 取值 left-最左边,right-左右边
     * @param key 键
     * @param value 值-数组类型
     * @return 0L 或 列表长度
     */
    public Long addList(String side, String key, Object[] value) {

        if (side == null || "".equals(side)
                || key == null || "".equals(key)
                || value == null || value.length <= 0) {
            return 0L;
        }

        // 最左边
        if ("left".equals(side)) {
            return redisTemplate.opsForList().leftPushAll(key, value);
        }
        else if ("right".equals(side)) {
            return redisTemplate.opsForList().rightPushAll(key, value);
        }

        return 0L;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key      键
     * @param seconds  时长 单位: 秒
     */
    public Boolean expire(String key, long seconds) {

        if (key == null || "".equals(key)
                || seconds <= 0) {
            return false;
        }

        boolean flag = false;
        try {
            flag = redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw e;
        }

        return flag;
    }
}

测试

package org.example.test;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import org.example.model.Student;
import org.example.redis.RedisClient;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * PackageName org.example.test
 *
 * @Author Eason
 * @Version v1.0
 * @ClassName TestRedisClient
 * @Date 2025/7/27
 * @Description TODO
 */
@SpringBootTest
public class TestRedisClient {

    @Resource
    private RedisClient redisClient;

    @Test
    public void TestSet() {

        var stu = new Student();
        stu.setName("张三");
        stu.setAge(16);

        redisClient.setHashWithTime("student", "1111", stu, 10000);

        var stu_ = redisClient.getHashForType("student", "1111", Student.class);

        System.out.println(JSON.toJSONString(stu_));

    }

}

### 整合 RedisSpring Boot 3 的教程 在现代应用程序开发中,Redis 是一种广泛使用的内存数据存储解决方案。通过将其集成到 Spring Boot 应用程序中,可以显著提高性能并支持缓存功能。以下是关于如何在 Spring Boot 3整合 Redis 的详细说明。 #### 配置依赖项 为了使 Spring BootRedis 能够协同工作,需要引入必要的 Maven 或 Gradle 依赖项。这些依赖项提供了与 Redis 进行交互所需的功能库[^1]。 对于 Maven 构建工具,可以在 `pom.xml` 文件中添加以下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 如果计划使用 Lettuce 客户端 --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` 如果项目基于 Gradle,则应在 `build.gradle` 文件中加入如下配置: ```gradle implementation &#39;org.springframework.boot:spring-boot-starter-data-redis&#39; // 可选:Lettuce 客户端 implementation &#39;io.lettuce.core:lettuce-core&#39; ``` 上述依赖会自动导入所需的类和方法来操作 Redis 数据库[^2]。 --- #### 配置文件设置 完成依赖项的添加之后,在项目的 `application.properties` 或者 `application.yml` 文件中定义 Redis 的连接参数。例如: ##### 使用 application.properties: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.database=0 ``` ##### 使用 application.yml: ```yaml spring: redis: host: localhost port: 6379 password: "" database: 0 ``` 以上属性指定了 Redis 实例的位置以及访问权限等信息[^3]。 --- #### 创建 Redis 配置类 可以通过创建自定义配置类进一步调整默认行为或者启用特定特性。下面是一个简单的例子展示如何声明一个 Bean 来管理 RedisTemplate 对象实例化过程中的序列化策略。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory){ return new StringRedisTemplate(connectionFactory); } } ``` 此代码片段展示了如何利用 Spring 提供的支持机制轻松实现对字符串键值对的操作能力提升效率的同时也增强了灵活性。 --- #### 编写服务逻辑 最后一步就是编写实际业务逻辑去调用 Redis 功能了。这里给出一段示范性的 Java 方法用于保存及检索用户登录状态记录至 Redis 缓存之中: ```java @Service public class LoginService { private final StringRedisTemplate template; public LoginService(StringRedisTemplate template) { this.template = template; } public void saveLoginStatus(String userId, boolean status) { template.opsForValue().set(userId, Boolean.toString(status)); } public Optional<Boolean> getLoginStatus(String userId) { String value = template.opsForValue().get(userId); if (value != null && !value.isEmpty()) { return Optional.of(Boolean.parseBoolean(value)); } else { return Optional.empty(); } } } ``` 这段示例演示了一个典型场景——即当某个用户的在线离线情况发生变化时更新其对应的标记位;而查询部分则负责读取当前已知的状态以便后续处理流程继续执行下去。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值