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
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
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
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
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 那么
configMap.put("xxx", config.entryTtl(Duration.ofSeconds(120)));
keyGenerator为缓存策略,可根据需求修改