SpringBoot整合redis简单实现
1.创建springboot项目
pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.hz</groupId> <artifactId>cn-web</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>RELEASE</version> </dependency> </dependencies> </project>
AppRun.java
1 2 3 4 5 6 7 8 9 10 11 | import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AppRun { public static void main(String[] args) { SpringApplication.run(AppRun. class , args); } } |
RedisService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisService { @Autowired private RedisTemplate<String,String> redisTemplate; //设置值 public void set(String key, String val){ redisTemplate.opsForValue().set(key,val); } //设置值,及过期时间 public void set(String key, String val, Integer seconds){ redisTemplate.opsForValue().set(key,val); redisTemplate.expire(key, seconds, TimeUnit.SECONDS); } //过期时间 public void expire(String key, Integer seconds){ redisTemplate.expire(key, seconds, TimeUnit.SECONDS); } //获取值 public String get(String key){ return redisTemplate.opsForValue().get(key).toString(); } } |
TestRedis.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | import redis.clients.jedis.Jedis; public class TestRedis { public static void main(String[] args) { // 设置连接服务器IP地址和访问端口 Jedis jedis = new Jedis( "192.168.187.142" , 6379 ); String s = jedis.get( "name" ); System.out.println(s); } } |
前提:关闭防火墙,关闭redis保护模式
二.使用注解Cacheable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | package com.foton.framework.conf; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import java.time.Duration; import java.util.*; /** * <p> * Redis Cache配置 * </p> * @author gao.fx * @date 2018-11-08 */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { StringBuffer redisKey = new StringBuffer(); redisKey.append(target.getClass().getName()).append( "-" ); redisKey.append(method.getName()); if (params.length > 0 ) { redisKey.append( "-" ).append(Arrays.deepToString(params)); } return redisKey.toString(); }; } @Bean @Primary public CacheManager simpleCacheManager(RedisConnectionFactory factory) { // 生成一个默认配置,通过config对象即可对缓存进行自定义配置 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存的默认过期时间,也是使用Duration设置 // 过期时间5分钟 config = config.entryTtl(Duration.ofMinutes( 30 )); // 设置一个初始化的缓存空间set集合 Set<String> cacheNames = new HashSet<>(); cacheNames.add( "my-redis-cache1" ); cacheNames.add( "my-redis-cacheX" ); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>( 10 ); configMap.put( "my-redis-cache1" , config); configMap.put( "my-redis-cache2" , config.entryTtl(Duration.ofSeconds( 120 ))); // 使用自定义的缓存配置初始化一个cacheManager RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config.entryTtl(Duration.ofMinutes( 30 ))) // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置 .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } } |
注意:
坑:@Bean修饰的方法名如果重复,只能读取第一次加载的,后者方法将不会生效!
我们可以对于一些定制话的业务设置不同的失效时间 例如 redis的key是 xxx 那么
1 | configMap.put( "xxx" , config.entryTtl(Duration.ofSeconds( 120 )));<br><br> |
1 | keyGenerator为缓存策略,可根据需求修改 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?