项目正常创建 建好之后
在application文件加入 此处为yml,properties同理
redis:
database: 0
host: 1.117.92.19
port: 6379
#连接超时时间 单位 ms(毫秒)
timeout: 3000
导入pom唯一依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置缓存
package com.test.config;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.cache.CacheManager;
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.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
@EnableCaching
public class CacheConfig{
private static final Logger log = Logger.getLogger(CacheConfig.class);
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName("127.0.0.1");
redisConnectionFactory.setPort(6379);
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//这里可以设置一个默认的过期时间
cacheManager.setDefaultExpiration(300);
return cacheManager;
}
@Bean
public KeyGenerator customKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
接口实现类添加注解
package com.test.service.impl;
@Service
public class UserServiceImpl implements UserService{
@CachePut(cacheNames="user",key="#result.id")
@CacheEvict(cacheNames="countUser" ,allEntries = true)
@Override
public User addUser(User user) {
userDao.add(user);
return user;
}
addUser()方法有两个注解,@CachePut(cacheNames=”user”,key=”#result.id”)表示,执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。可以是添加用户之后直接加入缓存,并且指定key是返回值的id。则下次使用该id去查询user的时候可以直接从缓存中获取。