1、引入 spring-boot-starter-redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、添加配置文件
spring:
redis:
database: 0 # Redis数据库索引(默认为0)
host: localhost # Redis服务器地址
port: 6379 # Redis服务器连接端口(默认为6379)
password: 970713 # Redis服务器连接密码(默认为空)
timeout: 60s # 数据库连接超时时间,2.0 中该参数的类型为Duration,配置的时候需要指明单位
jedis:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
3.缓存的配置类
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
/**
* 自动生成Key,作为Redis的Key
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 缓存管理器
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheManager cacheManager = RedisCacheManager.create(factory);
return cacheManager;
}
/**
* 配置RedisTemplate
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(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);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4.配置完成后,进行测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() {
stringRedisTemplate.opsForValue().set("aaa", "111");
System.out.println(stringRedisTemplate.opsForValue().get("aaa"));
}
@Test
public void testObj() throws InterruptedException {
User user = new User(null, "yuxia", "111111", "123@qq.com",
"yuxia", "2018-10-12 09:52:55");
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set("com.yuxia1", user);
operations.set("com.yuxia.f", user, 1, TimeUnit.SECONDS);// 设置1s后过期
Thread.sleep(1000);// 线程暂停1s后,com.yuxia.f过期
// redisTemplate.delete("com.yuxia.f");
boolean exists = redisTemplate.hasKey("com.yuxia.f");
if (exists) {
System.out.println("exists is true");
} else {
System.out.println("exists is false");
}
}
}
5.自动根据方法,生成缓存
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser(){
User user=userRepository.findByUserName("yuxia");
System.out.println("再次访问,不会输出");
return user;
}
}
注意:如果使用了热部署,会报错:java.lang.ClassCastException: com.example.demo.domain.User cannot be cast to com.example.demo.domain.User
网友评论