您好,欢迎访问一九零五行业门户网

SpringBoot集成Redis开启缓存机制的方法

集成springboot+redis+mybatis plus的一个小demopom文件<?xml version="1.0" encoding="utf-8"?><project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.wlient</groupid> <artifactid>springboot_mq_redis</artifactid> <version>0.0.1-snapshot</version> <name>springboot_mq_redis</name> <description>demo project for spring boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <spring-boot.version>2.3.7.release</spring-boot.version> </properties> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-amqp</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>com.baomidou</groupid> <artifactid>mybatis-plus-boot-starter</artifactid> <version>3.4.2</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <scope>runtime</scope> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> <exclusions> <exclusion> <groupid>org.junit.vintage</groupid> <artifactid>junit-vintage-engine</artifactid> </exclusion> </exclusions> </dependency> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework.amqp</groupid> <artifactid>spring-rabbit-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.9.6</version> </dependency> <!--jedis--> <dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> <version>3.2.0</version> </dependency> <!-- swagger --> <dependency> <groupid>com.github.xiaoymin</groupid> <artifactid>knife4j-spring-boot-starter</artifactid> <version>2.0.7</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.76</version> </dependency> </dependencies> <dependencymanagement> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-dependencies</artifactid> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencymanagement> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <version>2.3.7.release</version> <configuration> <mainclass>com.wlient.springboot_mq_redis.springbootmqredisapplication</mainclass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build></project>
yaml文件spring: redis: host: 1.117.89.11 port: 6378 password: terry123456. timeout: 60s database: 2 lettuce: pool: # 连接池中的最小空闲连接 min-idle: 0 # 连接池中的最大空闲连接 max-idle: 8 # 连接池的最大数据库连接数 max-active: 8 # #连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1ms #spring cache 配置 cache: type: redis redis: # key过期时间 半小时 time-to-live: 1800000 #毫秒
cacheconfig@configurationpublic class cacheconfig { @bean cachemanager cachemanager(redisconnectionfactory connectionfactory) { rediscacheconfiguration defaultcacheconfig = rediscacheconfiguration.defaultcacheconfig(); //common信息缓存配置 rediscacheconfiguration usercacheconfiguration = defaultcacheconfig // 设置 key为string序列化 .serializekeyswith(redisserializationcontext.serializationpair.fromserializer(new stringredisserializer())) // 设置value为json序列化 .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(new genericjackson2jsonredisserializer())).disablecachingnullvalues(); map<string, rediscacheconfiguration> rediscacheconfigurationmap = new hashmap<>(); //entryttl设置缓存失效时间,单位是秒 rediscacheconfigurationmap.put("common", usercacheconfiguration.entryttl(duration.ofseconds(30))); //设置cachemanager的值序列化方式为jdkserializationredisserializer,但其实rediscacheconfiguration默认就是使用stringredisserializer序列化key,jdkserializationredisserializer序列化value,所以以下注释代码为默认实现 //classloader loader = this.getclass().getclassloader(); //jdkserializationredisserializer jdkserializer = new jdkserializationredisserializer(loader); //redisserializationcontext.serializationpair<object> pair = redisserializationcontext.serializationpair.fromserializer(jdkserializer); //rediscacheconfiguration defaultcacheconfig=rediscacheconfiguration.defaultcacheconfig().serializevalueswith(pair); set<string> cachenames = new hashset<>(); cachenames.add("common"); //初始化rediscachemanager rediscachemanager cachemanager = rediscachemanager.builder(connectionfactory).cachedefaults(defaultcacheconfig).initialcachenames(cachenames).withinitialcacheconfigurations(rediscacheconfigurationmap).build(); return cachemanager; }}
redisconfigpackage com.wlient.springboot_mq_redis.configuar;import com.fasterxml.jackson.annotation.jsonautodetect;import com.fasterxml.jackson.annotation.propertyaccessor;import com.fasterxml.jackson.databind.objectmapper;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.jackson2jsonredisserializer;import org.springframework.data.redis.serializer.stringredisserializer;@configurationpublic class redisconfig { @bean @suppresswarnings("all") public redistemplate<string, object> redistemplate(redisconnectionfactory factory) { redistemplate<string, object> template = new redistemplate<string, object>(); template.setconnectionfactory(factory); jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class); objectmapper om = new objectmapper(); om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any); om.enabledefaulttyping(objectmapper.defaulttyping.non_final); jackson2jsonredisserializer.setobjectmapper(om); stringredisserializer stringredisserializer = new stringredisserializer(); // key采用string的序列化方式 template.setkeyserializer(stringredisserializer); // hash的key也采用string的序列化方式 template.sethashkeyserializer(stringredisserializer); // value序列化方式采用jackson template.setvalueserializer(jackson2jsonredisserializer); // hash的value序列化方式采用jackson template.sethashvalueserializer(jackson2jsonredisserializer); template.afterpropertiesset(); return template; }}
springcacheconfigpackage com.wlient.springboot_mq_redis.configuar;import org.springframework.boot.autoconfigure.cache.cacheproperties;import org.springframework.boot.context.properties.enableconfigurationproperties;import org.springframework.cache.annotation.enablecaching;import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.data.redis.cache.rediscacheconfiguration;import org.springframework.data.redis.serializer.redisserializationcontext;import org.springframework.data.redis.serializer.redisserializer;/** * spring cache 配置 */@enableconfigurationproperties(cacheproperties.class)@configuration@enablecachingpublic class springcacheconfig { @bean public rediscacheconfiguration rediscacheconfiguration(cacheproperties cacheproperties) { rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig() .serializekeyswith(redisserializationcontext.serializationpair.fromserializer(redisserializer.string())) .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(redisserializer.json())); cacheproperties.redis redisproperties = cacheproperties.getredis(); //将配置文件中所有的配置都生效 if (redisproperties.gettimetolive() != null) { config = config.entryttl(redisproperties.gettimetolive()); } if (redisproperties.getkeyprefix() != null) { config = config.prefixkeyswith(redisproperties.getkeyprefix()); } if (!redisproperties.iscachenullvalues()) { config = config.disablecachingnullvalues(); } if (!redisproperties.isusekeyprefix()) { config = config.disablekeyprefix(); } return config; }}
redisservicepackage com.wlient.springboot_mq_redis.service;import org.springframework.beans.factory.annotation.autowired;import org.springframework.data.redis.core.redistemplate;import org.springframework.stereotype.service;import org.springframework.util.collectionutils;import javax.annotation.resource;import java.util.collection;import java.util.list;import java.util.map;import java.util.set;import java.util.concurrent.timeunit;@servicepublic class redisservice { @resource private redistemplate<string, object> redistemplate; // =============================common============================ /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(string key, long time) { try { if (time > 0) { redistemplate.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 redistemplate.getexpire(key, timeunit.seconds); } /** * 判断key是否存在 * @param key 键 * @return true 存在 false不存在 */ public boolean haskey(string key) { try { return redistemplate.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) { redistemplate.delete(key[0]); } else { redistemplate.delete(collectionutils.arraytolist(key)); } } } // ============================string============================= /** * 普通缓存获取 * @param key 键 * @return 值 */ public object get(string key) { return key == null ? null : redistemplate.opsforvalue().get(key); } /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(string key, object value) { try { redistemplate.opsforvalue().set(key, value); return true; } catch (exception e) { e.printstacktrace(); 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) { redistemplate.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 redistemplate.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 redistemplate.opsforvalue().increment(key, -delta); } // ================================map================================= /** * hashget * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public object hget(string key, string item) { return redistemplate.opsforhash().get(key, item); } /** * 获取hashkey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public map<object, object> hmget(string key) { return redistemplate.opsforhash().entries(key); } /** * hashset * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(string key, map<string, object> map) { try { redistemplate.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 { redistemplate.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 { redistemplate.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 { redistemplate.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) { redistemplate.opsforhash().delete(key, item); } /** * 删除hash表中的值 * @param key 键 不能为null * @param items 项 可以使多个 不能为null */ public void hdel(string key, collection items) { redistemplate.opsforhash().delete(key, items.toarray()); } /** * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hhaskey(string key, string item) { return redistemplate.opsforhash().haskey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param delta 要增加几(大于0) * @return */ public double hincr(string key, string item, double delta) { if (delta < 0) { throw new runtimeexception("递增因子必须大于0"); } return redistemplate.opsforhash().increment(key, item, delta); } /** * hash递减 * @param key 键 * @param item 项 * @param delta 要减少记(小于0) * @return */ public double hdecr(string key, string item, double delta) { if (delta < 0) { throw new runtimeexception("递减因子必须大于0"); } return redistemplate.opsforhash().increment(key, item, -delta); } // ============================set============================= /** * 根据key获取set中的所有值 * @param key 键 * @return */ public set<object> sget(string key) { try { return redistemplate.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 redistemplate.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 redistemplate.opsforset().add(key, values); } catch (exception e) { e.printstacktrace(); return 0; } } /** * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sset(string key, collection values) { try { return redistemplate.opsforset().add(key, values.toarray()); } 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 = redistemplate.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 redistemplate.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 = redistemplate.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 redistemplate.opsforlist().range(key, start, end); } catch (exception e) { e.printstacktrace(); return null; } } /** * 获取list缓存的长度 * @param key 键 * @return */ public long lgetlistsize(string key) { try { return redistemplate.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 redistemplate.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 { redistemplate.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 { redistemplate.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 { redistemplate.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 { redistemplate.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 { redistemplate.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 = redistemplate.opsforlist().remove(key, count, value); return remove; } catch (exception e) { e.printstacktrace(); return 0; } }}
application@springbootapplication@mapperscan("com.wlient.springboot_mq_redis.dao")@enablecachingpublic class springbootmqredisapplication { public static void main(string[] args) { springapplication.run(springbootmqredisapplication.class, args); }}
主要是添加@enablecaching注解开启缓存
缓存有两种方式:
方式一:直接使用对redistemplate进行封装的redisservice进行缓存操作
controller层
@autowired redisservice redisservice; @getmapping("selectone2") public serviceresult<user> selectone2(integer id) { user user = (user) redisservice.get("selectone2::"+id); if (user == null){ user = userservice.querybyid2(id); redisservice.set("selectone2::"+id,user); } system.out.println(user); return serviceresult.ok(user); }
方式二:使用注解
作用于service层
@service("userservice")@cacheconfig(cachenames = "departmentsservice")public class userserviceimpl implements userservice { @resource private userdao userdao; /** * 通过id查询单条数据 * * @param id 主键 * @return 实例对象 */ @override @cacheable(key = "#root.methodname+':'+#id") public user querybyid(integer id) { user user = this.userdao.selectbyid(id); return user; }}
使用注解比较方便,但是不够灵活。
使用封装类增加了代码量,但是可以满足大部分需求
配置文件详解
redisconfig:redis cache,设置key,value的序列化方式等
springcacheconfig:spring cache 配置
这两个文件缺一不可,缺失springcacheconfig配置文件,那么存入redis的数据会乱码
cacheconfig:可有可无,只是根据需求采用的配置(从项目里copy的)
以上就是springboot集成redis开启缓存机制的方法的详细内容。
其它类似信息

推荐信息