SpringBoot学习篇13[整合Redis、自定义RedisTemplate、操作Redis、自定义Redis工具类]

1.引入依赖

有以下两种方式:

方式1:
在新建项目时勾选以下依赖即可
在这里插入图片描述
方式2:
手动将以下依赖添加进pom.xml文件中

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

2.配置Redis

配置Redis需要针对两方面进行配置。

一是连接属性

  • Redis服务器地址
  • Redis服务器端口号
  • 连接密码
  • 数据库索引
  • 超时时间

二是配置Redis连接池属性

  • 连接池大小
  • 等待时间
  • 空闲时间

SpringBoot默认使用的是lettuce连接池,这一点通过依赖关系就可以看到:
在这里插入图片描述
除此之外,还需要添加commons-pool2依赖,否则无法使用lettuce连接池

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
</dependency>

配置代码如下:

spring:
  redis:
    #设置服务器地址,默认为localhost
    host: 127.0.0.1
    #设置服务器端口号,默认为6379
    port: 6379
    #Redis默认不需要连接密码
    password:
    #设置数据库索引,默认为0
    database: 0
    #设置连接超时时间
    timeout: 5000ms
    lettuce:
      pool:
        #连接池大小,默认为8
        max-active: 20
        #最大空闲连接数
        max-idle: 20
        #最小空闲连接数,只有在time-between-eviction-runs设置为正值时才有效
        min-idle: 0
        #获取连接的最大阻塞等待时间(-1表示不限制)
        max-wait: 30s
        #空闲连接检查线程运行周期
        time-between-eviction-runs: 3000ms

3.操作Redis

Redis有五大数据类型:

  • String:<key,value>
  • Hash:<key,fields-values>
  • List:有顺序可重复
  • Set:无顺序不可重复
  • Zset(Sorted Sets):有顺序,不可重复

操作Redis即操作这五大数据类型,SpringBoot为我们提供了StringRedisTemplate和RedisTemplate用来操作Redis。StringRedisTemplate专门用来操作字符串,RedisTemplate可以用来操作复杂数据类型。接下来看一看他们怎么用吧。

3.1 操作字符串

示例代码如下

	@Autowired
    StringRedisTemplate stringRedisTemplate;
    
	@Test
    void StringRedisTemplateTest() {
        //设置或更新 key value
        stringRedisTemplate.opsForValue().set("name", "hello");
        //追加值
        stringRedisTemplate.opsForValue().append("name", "World");
        String nameValue = stringRedisTemplate.opsForValue().get("name");
        System.out.println(nameValue);

        stringRedisTemplate.opsForList().leftPush("list1", "aaa");
        stringRedisTemplate.opsForList().leftPush("list1", "bbb");
        stringRedisTemplate.opsForList().leftPush("list1", "ccc");
        List<String> list1 = stringRedisTemplate.opsForList().range("list1", 0, -1);
        System.out.println(list1);
    }

运行效果:
在这里插入图片描述
StringRedisTemplate类操作五大数据类型的API:

stringRedisTemplate.opsForValue();
stringRedisTemplate.opsForList();
stringRedisTemplate.opsForSet();
stringRedisTemplate.opsForZSet();
stringRedisTemplate.opsForHash();

3.2 操作复杂数据类型

准备工作,创建Employee类:

public class Employee {
    private Integer id;
    private String name;
    private Double salary;
    private Date birthday;

    public Employee(Integer id, String name, Double salary, Date birthday) {
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }
    public Employee() {
    }
	getter/setter方法
	toString方法
}

使用RedisTemplate操作复杂数据类型:

	@Autowired
    RedisTemplate redisTemplate;
	@Test
    void redisTemplateTest() {
        Employee employee1 = new Employee(1, "george", 13000D, new Date());
        Employee employee2 = new Employee(2, "peter", 13000D, new Date());
        Employee employee3 = new Employee(3, "mark", 13000D, new Date());

        redisTemplate.opsForValue().set("employee::1", employee1);

        Employee e = (Employee) redisTemplate.opsForValue().get("employee::1");
        System.out.println(e);


        redisTemplate.opsForList().leftPush("employees", employee1);
        redisTemplate.opsForList().leftPush("employees", employee2);
        redisTemplate.opsForList().leftPush("employees", employee3);

        List<Employee> employees = redisTemplate.opsForList().range("employees", 0, -1);
        System.out.println(employees);


    }

在执行过程中,你会发现出现了以下错误:
在这里插入图片描述
这是因为如果想要将象存储到Redis,需要将对象进行序列化,这样才能将对象转换成字节流,以及将字节流转换成对象读取出来。
序列化方法很简单,Employee 类实现Serializable接口就可以了:

public class Employee implements Serializable {
    private Integer id;
    private String name;
    private Double salary;
    private Date birthday;
    ......
}

运行效果
在这里插入图片描述
数据库中存储employee::1对象的序列化信息
在这里插入图片描述
数据库中存储employees的序列化信息
在这里插入图片描述
可以发现,在使用默认的RedisTemplate存储复杂类型数据时,无论是key还是value都是采用JDK提供的序列化方式进行存储的。这就导致了我们查看数据库时一点也不方便,这时就需要我们自定义RedisTemplate了。

4.自定义Redis

我们需要自定义一个RedisTemplate,并将其默认的序列化器指定为JSON序列化器,这样我们就能看懂数据库里的数据了。

4.1 自定义RedisTemplate

要想使用JSON序列化器需要引入依赖spring-boot-starter-json

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-json</artifactId>
</dependency>

编写配置类config.RedisConfig

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setDefaultSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

4.2 使用自定义RedisTemplate

	@Autowired
    RedisTemplate jsonRedisTemplate;
	@Test
    void jsonRedisTemplateTest() {
        Employee employee1 = new Employee(1, "george", 13000D, new Date());
        Employee employee2 = new Employee(2, "peter", 13000D, new Date());
        Employee employee3 = new Employee(3, "mark", 13000D, new Date());

        jsonRedisTemplate.opsForValue().set("employee::" + employee1.getId(), employee1);
        jsonRedisTemplate.opsForValue().set("employee::" + employee2.getId(), employee2);

        Employee e = (Employee) jsonRedisTemplate.opsForValue().get("employee::1");
        System.out.println(e);


        jsonRedisTemplate.opsForList().leftPush("employees", employee1);
        jsonRedisTemplate.opsForList().leftPush("employees", employee2);
        jsonRedisTemplate.opsForList().leftPush("employees", employee3);

        List<Employee> employees = jsonRedisTemplate.opsForList().range("employees", 0, -1);
        System.out.println(employees);


    }

运行效果:
在这里插入图片描述
数据库中存储的数据:
在这里插入图片描述
这样就清晰明了了。

5.自定义Redis工具类

每次操作数据前面都跟上一大串:jsonRedisTemplate.opsForValue().xxxx,jsonRedisTemplate.opsForList().xxxx…实在麻烦。
下面贴上一个自定义Redis工具类,参考自https://blog.csdn.net/qq_19734597/article/details/92798699(在此感谢作者的无私分享)

package com.springboot.utils;

/**
 * @Auther: yky
 */

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;

/**
 * Redis工具类
 */
@Component
public class RedisClient {

    @Autowired
    private RedisTemplate jsonRedisTemplate;

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    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) {
            e.printStackTrace();
            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));
            }
        }
    }

    public void del(Integer key) {
        this.del(String.valueOf(key));
    }

    // ============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : jsonRedisTemplate.opsForValue().get(key);
    }

    public Object get(Integer key) {
        return this.get(String.valueOf(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) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(Integer key, Object value) {
       return this.set( String.valueOf(key) , value);
    }
        /**
         * 普通缓存放入并设置时间
         * @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)
         * @return
         */
    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)
         * @return
         */
    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
         * @return 值
         */
    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 对应多个键值
         * @return true 成功 false 失败
         */
    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)
         * @return
         */
    public double hincr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, by);
    }
        /**
         * hash递减
         * @param key 键
         * @param item 项
         * @param by 要减少记(小于0)
         * @return
         */
    public double hdecr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, -by);
    }

        // ============================set=============================
        /**
         * 根据key获取Set中的所有值
         * @param key 键
         * @return
         */
    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 键
         * @return
         */
    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代表所有值
         * @return
         */
    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 键
         * @return
         */
    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倒数第二个元素,依次类推
         * @return
         */
    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 值
         * @return
         */
    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 时间(秒)
         * @return
         */
    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;
        }
    }
}

简单使用它

	@Autowired
    RedisClient redisClient;
    @Test
    void redisClientTest()
    {
        redisClient.set("employee::3", new Employee(3, "mark", 13000D, new Date()));
        redisClient.set("key1", "value1");

        Employee e = (Employee) redisClient.get("employee::3");
        String value = (String) redisClient.get("key1");
        System.out.println(e);
        System.out.println(value);

        redisClient.hset("myHash","employee::1", new Employee(1, "george", 13000D, new Date()));
        redisClient.hset("myHash","employee::2", new Employee(2, "peter", 13000D, new Date()));
        redisClient.hset("myHash","employee::3", new Employee(3, "mark", 13000D, new Date()));

        e = (Employee) redisClient.hget("myHash", "employee::1");
        System.out.println(e);

        Map<Object,Object> maps = redisClient.hmget("myHash");
        System.out.println(maps);
    }

控制台输出:
在这里插入图片描述

发布了41 篇原创文章 · 获赞 18 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章