目錄
1.引入依賴
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>springboot_redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--集成redis需要的依賴 begin-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--用於redis序列化 begin-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--用於redis序列化 end-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--集成redis需要的依賴 end-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(1)配置application.properties
spring.redis.host=127.0.0.1
#Redis服務器連接端口
spring.redis.port=6379
#Redis服務器連接密碼(默認爲空)
spring.redis.password=
#連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
#連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
#連接池中的最大空閒連接
spring.redis.pool.max-idle=8
#連接池中的最小空閒連接
spring.redis.pool.min-idle=0
#連接超時時間(毫秒)
spring.redis.timeout=30000
spring.redis.database=0
(2)新增配置類RedisConfig.java
package com.springboot.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.cache.RedisCacheWriter;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
// .entryTtl(Duration.ofSeconds(60))
// .disableCachingNullValues();
//
// return RedisCacheManager.builder(factory)
// .cacheDefaults(config)
// .transactionAware()
// .build();
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(factory),
this.getRedisCacheConfigurationWithTtl(60), // 默認策略,未配置的 key 會使用這個
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
redisCacheConfigurationMap.put("user", this.getRedisCacheConfigurationWithTtl(30)); // 單獨設置某些cache的超時時間
return redisCacheConfigurationMap;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
// 當沒有指定緩存的 key時來根據類名、方法名和方法參數來生成key
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append('.').append(method.getName());
if (params.length > 0) {
sb.append('[');
for (Object obj : params) {
sb.append(obj.toString());
}
sb.append(']');
}
System.out.println("keyGenerator=" + sb.toString());
return sb.toString();
}
};
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
// 設置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);
// RedisCacheConfiguration defaultCacheConfig =
// RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(getJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
@Primary
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
// 設置key序列化類,否則key前面會多了一些亂碼
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
//設置value序列化
template.setValueSerializer(getJackson2JsonRedisSerializer());
template.afterPropertiesSet();
template.setEnableTransactionSupport(true);
return template;
}
private Jackson2JsonRedisSerializer getJackson2JsonRedisSerializer() {
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);
return jackson2JsonRedisSerializer;
}
}
package com.springboot.redis.service;
import com.springboot.redis.po.Student;
/**
* @Package: com.springboot.redis.service
* @ClassName: IStudentService
* @author: zq
* @since: 2020/6/14 10:40
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
public interface IStudentService {
void put(String key, String value);
String get(String key);
String getName(int id);
int getId(int id);
Student getStudent(int id, String name);
}
package com.springboot.redis.service;
import com.springboot.redis.po.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
/**
* IStudentService 實現類
*
* @Package: com.springboot.redis.service
* @ClassName: StudentServiceImpl
* @author: zq
* @since: 2020/6/14 10:41
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
@Service
public class StudentServiceImpl implements IStudentService {
@Autowired
private RedisTemplate template;
@Override
public void put(String key, String value) {
template.opsForValue().set(key, value);
}
@Override
public String get(String key) {
return String.valueOf(template.opsForValue().get(key));
}
@Cacheable(value = "user", key = "#id", condition = "#id lt 1")
@Override
public String getName(int id) {
return "我真是張三";
}
@Cacheable(value = "user", key = "#id", condition = "#id lt 10")
@Override
public int getId(int id) {
return id;
}
@Cacheable(value = "user", key = "#id+#name", condition = "#id lt 10")
@Override
public Student getStudent(int id, String name) {
return new Student(id, name);
}
}
實體類
package com.springboot.redis.po;
import java.io.Serializable;
/**
* 學生類
*
* @Package: com.springboot.redis.po
* @ClassName: Student
* @author: zq
* @since: 2020/6/14 16:22
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
public class Student implements Serializable {
/**
* id
*/
private int id;
/**
* name
*/
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Student{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
public Student() {
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
package com.springboot.redis.controller;
import com.springboot.redis.po.Student;
import com.springboot.redis.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 學生控制器
*
* @Package: com.springboot.redis.controller
* @ClassName: StudentController
* @author: zq
* @since: 2020/6/14 10:37
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
@RestController
public class StudentController {
@Autowired
private IStudentService studentService;
@GetMapping("/put")
public Object put(String key, String value) {
studentService.put(key, value);
return "值已經被放入redis中了";
}
@GetMapping("/get")
public Object get(String key) {
String value = studentService.get(key);
return key + ":" + value;
}
@GetMapping("/getName")
public Object getName(int id) {
String name = studentService.getName(id);
return id + ":" + name;
}
@GetMapping("/getId")
public Object getId(int id) {
int val = studentService.getId(id);
return id + ":" + val;
}
@GetMapping("/getStudent")
public Object getStudent(int id, String name) {
Student val = studentService.getStudent(id, name);
return id + ":" + val;
}
}