Spring boot redis注解
转自:http://blog.csdn.net/yy756127197/article/details/75092236
继上一篇的template编码方式使用redis
编码形式配置(一)
编码形式使用(二)
经过深入学习发现注解形式的更好用一些,省去一些繁琐的代码,使得你代码看起来更优雅
安装redis服务端请看编码形式配置(一)
1. pom.xml
添加jar包支持,使用springboot自带的redis启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 1
- 2
- 3
- 4
- 5
2. Redis配置文件
这里新加入了缓存管理器,来管理redis.
Spring 3.1 引入了基于注释(annotation)的缓存(cache)技术,它不是一个具体的缓存实现方案(例如EHCache 或者 OSCache、Redis等),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。
RedisConfig.java
import java.io.Serializable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
@Slf4j
@Configuration
@EnableCaching//启用缓存,这个注解很重要;
//继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
public class RedisConfig extends CachingConfigurerSupport{
//因为生产环境和开发环境使用不同的启动资源文件,所以使用了@Profile,用来指定使用的启动资源文件
@Configuration
@Profile(value={"dev"})//如果你不需要的话可以删掉
static class LocalConfiguration {
//从application.properties中获得以下参数
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Value("${redis.password}")
private String password;
/**
* 缓存管理器.
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {
CacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}
@Bean
public RedisTemplate<Serializable, Serializable> redisTemplate(
JedisConnectionFactory redisConnectionFactory) {
log.info("------------------------------------------");
log.info("-----------------local redis--------------");
log.info("------------------------------------------");
RedisTemplate<Serializable, Serializable> redisTemplate = new RedisTemplate<Serializable, Serializable>();
//key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
//所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现 ObjectRedisSerializer
//或者JdkSerializationRedisSerializer序列化方式;
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate
.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate
.setHashValueSerializer(new JdkSerializationRedisSerializer());
//以上4条配置可以不用
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(host);
redisConnectionFactory.setPort(port);
redisConnectionFactory.setPassword(password);
return redisConnectionFactory;
}
}
/**
* 自定义key.
* 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key
*/
@Override
public KeyGenerator keyGenerator() {
log.info("RedisCacheConfig.keyGenerator()");
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects)
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
log.info("keyGenerator=" + sb.toString());
return sb.toString();
}
};
}
}
- 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
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
@Profile(value={“dev”})代表开发环境用的配置
@Slf4j 是lombok中的注解,不用的可以删掉
3. 使用事例
import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
@Slf4j
@Transactional
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
// keyGenerator="myKeyGenerator"//因为配置文件继承了CachingConfigurerSupport,所以不用指定了,也可以指定,就不会使用默认的key生成策略
@Cacheable(value = "userInfo", key = "'findUser' + #id")
// 缓存,这里没有指定key.
@Override
public UserDto findProperty(String id) {
UserDto user = userDao.findUser(id);
return user;
}
//删除指定缓存
@Override
//@CacheEvict(value="propertyInfo",allEntries=true) 清空全部
@CacheEvict(value = "propertyInfo", key = "'findUser' + #id")
public Ivoid cacheEvict(String id) {
log.info("删除缓存" + id);
}
}