Spring-data-redis

spring-data-jpa         spring-data-jdbc         spring-data-redis

说明: 在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce

jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接池

lettuce : 采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据 了

1.加入Redis相关依赖

 2.application.properties中加入redis相关配置

# Redis数据库索引(默认为0)  

spring.redis.database=0  

# Redis服务器地址  

spring.redis.host=192.168.0.24  

# Redis服务器连接端口  

spring.redis.port=6379  

# Redis服务器连接密码(默认为空)  

spring.redis.password=  

# 连接池最大连接数(使用负值表示没有限制)  

spring.redis.pool.max-active=200  

# 连接池最大阻塞等待时间(使用负值表示没有限制)  

spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接  

spring.redis.pool.max-idle=10

# 连接池中的最小空闲连接  

spring.redis.pool.min-idle=0  

# 连接超时时间(毫秒)  

spring.redis.timeout=1000

3.具体代码了解 

spring data redis中封装了两个模板类,帮助我们实现redis的crud

RedisTemplate                   key value泛型都是object

StringRedisTemplate         key value泛型都是string

注意:

         1.两者数据各自存,各自取,数据不互通。

                RedisTemplate不能取StringRedisTemplate存入的数据

                StringRedisTemplate不能取RedisTemplate存入的数据

         2.序列化策略不同:

                 RedisTemplate采用JDK的序列化策略(JdkSerializationRedisSerializer)保存的key 和value 都是采用此策略序列化保存的 存储时,先将数据序列化为字节数组,再存入Redis数据库。查看Redis会发现,是字节数组的形式类似乱码读取时,会将数据当做字节数组转化为我们需要的数据,以用来存储对象,但是要实现 Serializable接 口 StringRedisTemplate采用String的序列化策略(StringRedisSerializer)保存的key和 value都 是采用此策略序列化保存的当存入对象时,会报错:can not cast into String   存储和读取,都为可读的数据

         3.两者的关系是StringRedisTemplate继承RedisTemplate

         4.使用场景:   当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那 么你就使 用StringRedisTemplate即可。   但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取 出一个对   象,那么使用RedisTemplate是更好的选择。

五大数据类型

*         redisTemplate.opsForValue();//操作字符串

*         redisTemplate.opsForList();//操作List

*         redisTemplate.opsForSet();//操作Set

*         redisTemplate.opsForZSet();//操作ZSet

*         redisTemplate.opsForHash();//操作Hash

序列化策略  

改变序列化策略

默认序列化方式存储到redis的数据人工不可读

不同策略序列化的过程有性能高低的

spring-data-redis提供如下几种序列化策略

GenericToStringSerializer: 可以将任何对象泛化为字符串并序列化 Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer实际上是一样的 JacksonJsonRedisSerializer: 序列化object对象为json字符串 JdkSerializationRedisSerializer: 序列化java对象

StringRedisSerializer: 简单的字符串序列化

使用Redis结合三层框架做学生的查看与删除,第一次查看的时候Redis缓存中没有数据,所以会在数据库中查看结果,返回数据,第二次查看的时候就可以直接在缓存中查看

配置一个可以用于操作 Redis 数据库的 RedisTemplate 实例,设置了键和值的序列化方式,使得应用在与 Redis 交互时,可以方便地存储和获取数据。通过使用 JSON 格式的序列化,数据更易于阅读和管理。

  1. RedisTemplate<Object, Object>:

    • RedisTemplate 是 Spring Data Redis 提供的一个类,作为与 Redis 数据库交互的核心类。
    • 它使用泛型来指定键 (key) 和值 (value) 的类型。
  1. setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class)):

    • 这行代码设置默认的值序列化方式为 Jackson2JsonRedisSerializer,用于将对象序列化为 JSON 格式。
    • 这样,当存储对象到 Redis 时,会将对象转换为 JSON 字符串,便于后续获取和解析。
@Configuration
public class RedisConfig{
 
 
    @Bean
    public RedisTemplate<Object, Object> jsonRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setStringSerializer(new StringRedisSerializer());
        //配置json类型的序列化工具
        template.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
 
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("student")
public class Student {
    @TableId(value = "stu_id" ,type = IdType.AUTO)
    private Integer stuId;
    @TableField("stu_name")
    private String stuName;
    @TableField("stu_hobby")
    private String stuHobby;
 
 
}
public interface StudentMapper extends BaseMapper<Student>{
 
}

RedisUtil 类 

package com.ztt.springboot_redis02.utils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
// 在我们真实的开发中,一般都可以看到一个公司自己封装RedisUtil
@Component
public  class RedisUtil {
 
    @Autowired(required = false)
    private RedisTemplate jsonRedisTemplate;
    
    // =========================================================
    /**
     * 指定缓存失效时间
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                jsonRedisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return jsonRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
 
 
    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return jsonRedisTemplate.hasKey(key);
        } catch (Exception e) {
            return false;
        }
    }
 
 
    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                jsonRedisTemplate.delete(key[0]);
            } else {
                jsonRedisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
 
 
    // ============================String=============================
 
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : jsonRedisTemplate.opsForValue().get(key);
    }
    
    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
 
    public boolean set(String key, Object value) {
        try {
            jsonRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
 
    /**
     * 普通缓存放入并设置时间
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
 
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                jsonRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * 递增
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return jsonRedisTemplate.opsForValue().increment(key, delta);
    }
 
 
    /**
     * 递减
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return jsonRedisTemplate.opsForValue().increment(key, -delta);
    }
 
 
    // ================================Map=================================
 
    /**
     * HashGet
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
        return jsonRedisTemplate.opsForHash().get(key, item);
    }
    
    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return jsonRedisTemplate.opsForHash().entries(key);
    }
    
    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            jsonRedisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * HashSet 并设置时间
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            jsonRedisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            jsonRedisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            jsonRedisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        jsonRedisTemplate.opsForHash().delete(key, item);
    }
 
 
    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return jsonRedisTemplate.opsForHash().hasKey(key, item);
    }
 
 
    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, by);
    }
 
 
    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, -by);
    }
 
 
    // ============================set=============================
 
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     */
    public Set<Object> sGet(String key) {
        try {
            return jsonRedisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return jsonRedisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return jsonRedisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
 
    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = jsonRedisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
 
    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
        try {
            return jsonRedisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
 
    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
 
    public long setRemove(String key, Object... values) {
        try {
            Long count = jsonRedisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    // ===============================list=================================
    
    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return jsonRedisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
        try {
            return jsonRedisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
 
    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
    public Object lGetIndex(String key, long index) {
        try {
            return jsonRedisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
        try {
            jsonRedisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /**
     * 将list放入缓存
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            jsonRedisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
 
    }
 
 
    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            jsonRedisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
 
    }
 
 
    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            jsonRedisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
 
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            jsonRedisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
 
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = jsonRedisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
 
    }
 
}
 业务逻辑层

处理来自表示层的请求,并调用数据访问层的方法。

package com.ztt.springboot_redis02.service;
 
 
 
import com.ztt.springboot_redis02.pojo.Student;
import com.ztt.springboot_redis02.mapper.StudentMapper;
 
import com.ztt.springboot_redis02.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
 
@Service
public class StudentService {
 
 
    @Autowired(required = false)
    StudentMapper mapper;
 
    @Autowired
    public RedisUtil redisUtil;
 
 
    /**
     * 获取用户策略:先从缓存中获取用户,没有则取数据表中数据,再将数据写入缓存
     */
    public Student findById(Integer id){
        String key = "student:id:" + id;
 
        //1.1判断key在redis中是否存在
        boolean hasKey = redisUtil.hasKey(key);
        if (hasKey) {
            //1.2存在缓存则直接获取
            Object stu = redisUtil.get(key);
            ObjectMapper change = new ObjectMapper();
            Student student =   change.convertValue(stu,Student.class);
            System.out.println("==========从缓存中获得数据=========");
            System.out.println(student.getStuName());
            System.out.println("==============================");
            return student;
        } else {
            //1.3不存在缓存,先从数据库中获取,在保存至redis,最后返回用户
            Student student = mapper.selectById(id);
            System.out.println("==========从数据表中获得数据=========");
            System.out.println(student.getStuName());
            System.out.println("==============================");
            if (student != null){
                redisUtil.set(key, student);//写入缓存
            }
            return student;
        }
    }
 
 
    /**
     * 删除用户策略:删除数据表中数据,然后删除缓存
     *
     */
    public void deleteStudentById(Integer id){
        //1.删除数据库
        int result = mapper.deleteById(id);
        //2.判断数据库中是否删除成功
        String key = "student:id:" + id;
        if (result != 0) {
            //3.判断redis中是否存在
            boolean hasKey = redisUtil.hasKey(key);
            //4.存在删除,不存在直接跳转
            if (hasKey) {
                redisUtil.del(key);
                System.out.println("删除了缓存中的key:" + key);
            }
        }
    }
 
}
@RestController
public class StudentController {
 
    @Autowired
    StudentService stuService;
 
    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") Integer id) {
        Student stu = stuService.findById(id);
        return stu;
    }
@SpringBootApplication
@MapperScan("com.ztt.springboot_redis02.mapper")
public class SpringbootRedis02Application {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedis02Application.class, args);
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值