spring + RedisTemplate使用缓存

2024-08-26 09:18

本文主要是介绍spring + RedisTemplate使用缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

spring + RedisTemplate使用缓存

使用步骤

  • 配置文件, 只需要配置了 redisTemplate 就可以

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:property-placeholder location="classpath:config.properties" />
    
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxTotal" value="${redis.pool.maxActive}" />
            <property name="maxIdle" value="${redis.pool.maxIdle}" />
            <property name="maxWaitMillis" value="${redis.pool.maxWait}" />
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
        </bean>
    
        <bean id="connectionFactory"
              class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <property name="hostName" value="${redis.host}"/>
            <property name="port" value="${redis.port}"/>
            <property name="password" value="${redis.password}" />
            <property name="timeout" value="${redis.timeout}"/>
            <property name="database" value="${redis.database}"/>
            <property name="poolConfig" ref="jedisPoolConfig"/>
        </bean>
    
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory"   ref="connectionFactory" />
            <property name="keySerializer" ref="keySerializer"/>  <!-- key使用String序列化方式 -->
            <property name="hashKeySerializer" ref="keySerializer"/> 
            <property name="valueSerializer" ref="jackson2JsonRedisSerializer"/> <!-- value使用json序列化 -->
            <property name="hashValueSerializer" ref="jackson2JsonRedisSerializer"/>
            <!--<property name="hashValueSerializer" ref="jdkSerializer"/>-->
        </bean>
    
        <bean id="keySerializer"
              class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        <bean id="jackson2JsonRedisSerializer"
          class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        <bean id="jdkSerializer"
          class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
    </beans>
  • 测试

    package com.susq.redisdb;
    
    import com.susq.mysqldb.model.User;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.annotation.Resource;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @author susq
     * @since 2018-05-16-20:35
     */
    @Slf4j
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:spring-cache.xml")
    public class RedisTemplateApp {
    
        @Resource
        private RedisTemplate<String, User> redisTemplate;
    
        @Test /*redisTemplate.opsForValue()默认使用了redisTemplate配置的序列化方式*/
        public void putUser() {
            User user = new User("haha", "hangzhou");
            redisTemplate.opsForValue().set(user.getName(), user, 10, TimeUnit.SECONDS);
            User user1 = redisTemplate.opsForValue().get(user.getName());
            log.info(user1.toString());
        }
    
        @Test
        public void getUser() {
            User user = redisTemplate.opsForValue().get("haha");
            if (null == user) {
                log.info("不存在的");
                return;
            }
            log.info(user.toString());
        }
    
        @Test
        public void putUserSer() {
            User user = new User("haha", "hangzhou");
            redisTemplate.execute(new RedisCallback<User>() {
                @Override
                public User doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    RedisSerializer<String> keySerializer = redisTemplate.getStringSerializer();
                    RedisSerializer<User> valueSerializer = (RedisSerializer<User>) redisTemplate.getValueSerializer();
                    byte[] keyBytes = keySerializer.serialize(user.getName());
                    byte[] valueBytes = valueSerializer.serialize(user);
                    redisConnection.setEx(keyBytes, 20, valueBytes);
                    byte[] value = redisConnection.get(keyBytes);
                    User user1 = valueSerializer.deserialize(value);
                    log.info("put结束后,再get出来验证:{}", user1);
                    return null;
                }
            });
            // 这个操作封装了获取value的字节后反序列化的操作,跟上面的先get得到byte[]再deserialize的到对象一样
            User user1 = redisTemplate.opsForValue().get(user.getName()); 
            log.info(user1.toString());
        }
    }

    redisTemplate.execute() 可以自己实现 RedisCallback 接口,更灵活一些。而直接使用redisTemplate.opsForValue(),redisTemplate.opsForHash()..... 这样的形式更方便简洁。

为什么序列化?

作者:大宽宽

链接:https://www.zhihu.com/question/277363840/answer/392945240

任何存储都需要序列化。只不过常规你在用DB一类存储的时候,这个事情DB帮你在内部搞定了(直接把SQL带有类型的数据转换成内部序列化的格式,存储;读取时再解析出来)。

而Redis并不会帮你做这个事情。当你用Redis的key和value时,value对于redis来讲就是个byte array。你要自己负责把你的数据结构转换成byte array,等读取时再读出来。

一个特例是字符串,因为字符串自己几乎就已经是byte array了,所以不需要自己处理。

因此当你要用redis存一个东西,你可能会遇到

  • 如果是boolean类型的true/false;你要自己定义redis里怎么表示true和false。比如你可以用1代表true,0代表false;也可以用“true”这个字符串代表true,“false”这个字符串代表false。

  • 如果是数字,可以直接存储数字的字符串表示(5 --> '5'),然后读取时再把数字字符串转回来(parseInt/parseDouble/...)。

  • 如果是时间/日期,可以自己定义一种字符串表达,比如epoc timestamp这个数的字符串表示,又或者是ISO8601的格式。

  • 如果是一个复杂的数据结构,你需要自己用某种序列化格式来存,可以是json, protobuf, avro, java serialization, python pickle……

回到Spring这边。Spring的redisTemplate默认会使用java serialization做序列化。你也可以用StringRedisTemplate,那么你set的所有数据都会被toString一下再存到redis里。但这个toString不一定能反解析的回来……

其他

spring @Cacheable @CachePut... 使用redis缓存详细步骤

spring + Jedis 的方式使用缓存

这篇关于spring + RedisTemplate使用缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108163

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。