SpringBoot整合Redis

前言

以前的笔记经过还原系统弄丢了,所以就在优快云中记录一下
Redis的基本操作就不用赘述了
主要就是记录SpringBoot整合redis所需要的东西
我这里主要看的是RuoYi框架编写的工具类与配置类

基本命令

下面就是基本的redis命令,其余什么的用到在查询即可(什么过期时间啥的)

{name=scan, value=4}
{name=set, value=4}
{name=del, value=2}
{name=info, value=4}
{name=auth, value=3}
{name=ttl, value=3}
{name=get, value=10}
{name=config, value=4}
{name=type, value=3}
{name=client, value=3}
{name=ping, value=4}
{name=keys, value=8}

引入依赖

<!-- springboot整合redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- pool 对象池 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

<!-- 阿里JSON解析器 -->
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.25</version>
</dependency>

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

配置文件

application.yml配置

spring:
	redis:
	    # Redis服务器地址
	    host: localhost
	    # Redis服务器端口号
	    port: 6379
	    # 使用的数据库索引,默认是0
	    database: 0
	    # 连接超时时间
	    timeout: 1800000
	    # 设置密码
	    password:
	    lettuce:
	      pool:
	        # 最大阻塞等待时间,负数表示没有限制
	        max-wait: -1
	        # 连接池中的最大空闲连接
	        max-idle: 5
	        # 连接池中的最小空闲连接
	        min-idle: 0
	        # 连接池中最大连接数,负数表示没有限制
	        max-active: 20

SpringBoot整合Redis默认使用的客户端是lettuce,所以上方配置的也是lettuce连接池

测试使用

@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
class StudentSpringSecurityApplicationTests {

    private final RedisTemplate<String, String> redisTemplate;

    @Test
    public void testRedis() {
        // 向redis中存储数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("name", "zhang-san");
        // 获取redis中存储的数据
        Object name = valueOperations.get("name");
        System.out.println(name);
        Properties execute = (Properties)redisTemplate.execute((RedisCallback) a -> a.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        pieList.stream().forEach(System.out::println);
    }

}

输出内容

zhang-san
{name=scan, value=4}
{name=set, value=4}
{name=del, value=2}
{name=info, value=4}
{name=auth, value=3}
{name=ttl, value=3}
{name=get, value=10}
{name=config, value=4}
{name=type, value=3}
{name=client, value=3}
{name=ping, value=4}
{name=keys, value=8}

默认上方的测试你在程序中看着是key=name,value=zhang-san,其实你可以使用连接redis的工具输入get name发现返回的是null,原本的name也变成了乱码+key的形式。如下(正好推荐一个redis连接工具,文件自取)
百度网盘地址:https://pan.baidu.com/s/1GK1_IDUFhGyzCtYq0dbsMw?pwd=kfjz
提取码: kfjz
在这里插入图片描述
原因是什么呢:使用RedisTemplat来进行get与set时会默认使用jdk序列化将key与value进行序列化,jdk默认序列化使用的ObjectOutPutStream将字符转成字节

也就说你需要自己指定序列化,也可以不指定那就是使用StringRedisTemplate

自定义RedisTemplat实现序列化

package com.example.studentspringsecurity.config;

import org.springframework.cache.annotation.EnableCaching;
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.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * ClassName:           RedisConfig
 * Package:             com.example.studentspringsecurity.config
 * Description:         redis配置类
 * DateTime:            2023/5/21
 *
 * @author: xx-zh
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        // 创建RedisTemplate对象
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
        // 设置Key/Value序列化
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        // hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        // 初始化实例
        template.afterPropertiesSet();
        // 返回
        return template;
    }
}

可以看到没有FastJson2JsonRedisSerializer这个类,因为这个类是自定义封装的。如下

package com.example.studentspringsecurity.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * Redis使用FastJson序列化
 * 
 * @author ruoyi
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    public FastJson2JsonRedisSerializer(Class<T> clazz)
    {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }
}

为什么不使用Redis自己封装的json序列化类(Jackson2JsonRedisSerializer等),原因是会带有类名,导致存储的数据过多,小来小去倒是没问题,数据过多就消耗资源了

自己封装redis工具类

这里没有什么太多讲解的地方就是将redisTemplate的方法再次封装起来,根据所有ADT抽象的概念就是是否存在,存,取,删,删多,设置有效(过期)时间等

package com.example.studentspringsecurity.common.core.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:           RedisCache
 * Package:             com.example.studentspringsecurity.common.core.redis
 * Description:         redis工具类
 * DateTime:            2023/5/21
 *
 * @author: xx-zh
 */
@Component
@RequiredArgsConstructor
public class RedisCache {

    private final RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取有效时间
     *
     * @param key Redis键
     * @return 有效时间
     */
    public long getExpire(final String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public boolean deleteObject(final Collection collection) {
        return redisTemplate.delete(collection) > 0;
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 删除Hash中的某条数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return 是否成功
     */
    public boolean deleteCacheMapValue(final String key, final String hKey) {
        return redisTemplate.opsForHash().delete(key, hKey) > 0;
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
}

解读上方redisTemplate.execute方法

又到了开心的读源码时间
先来一张小图压压惊
在这里插入图片描述
开始走码:直奔主题三参数execute方法

@Nullable
public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {

	Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
	Assert.notNull(action, "Callback object must not be null");

	RedisConnectionFactory factory = getRequiredConnectionFactory();
	RedisConnection conn = RedisConnectionUtils.getConnection(factory, enableTransactionSupport);

	try {

		boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
		RedisConnection connToUse = preProcessConnection(conn, existingConnection);

		boolean pipelineStatus = connToUse.isPipelined();
		if (pipeline && !pipelineStatus) {
			connToUse.openPipeline();
		}

		RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
		// 主要看这里,返回的就是它
		T result = action.doInRedis(connToExpose);

		// close pipeline
		if (pipeline && !pipelineStatus) {
			connToUse.closePipeline();
		}

		return postProcessResult(result, connToUse, existingConnection);
	} finally {
		RedisConnectionUtils.releaseConnection(conn, factory, enableTransactionSupport);
	}
}

最终返回方法postProcessResult(result, connToUse, existingConnection);

@Nullable
protected <T> T postProcessResult(@Nullable T result, RedisConnection conn, boolean existingConnection) {
	return result;
}

可以看到,返回的就是result对象也就是execute中的action调用doInRedis方法返回的对象
但是进入RedisCallback定义的doInRedis方法返回的类型为T,接受的参数为RedisCollection,也就是说调用RedisCollection的什么方法就返回对应值返回值,简单来说就是doInRedis返回的是RedisCollection调用方法所返回的对象。上方调用的是info方法,RedisCollection实现info方法的为其实现类DefaultStringRedisConnection,最终执行convertAndReturn(交换并返回)方法,所返回的对象就是Properties
在这里插入图片描述

后续在补充:限流脚本等操作,因为暂时还没用到,先涉及广度即可

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值