整合缓存中间件redis(个人博客)
1、pom.xml依赖导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<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>
2、编写配置文件redisConfig.yml
spring:
redis:
host: 127.0.0.1
#Redis服务器连接端口
port: 6379
#Redis服务器连接密码(默认为空)yml
password:
#连接池最大连接数(使用负值表示没有限制)
pool.max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
pool.max-wait: -1
#连接池中的最大空闲连接
pool.max-idle: 8
#连接池中的最小空闲连接
pool.min-idle: 0
#连接超时时间(毫秒)
timeout: 30000
3、编写配置类RedisConfig
@Configuration
@EnableCaching
@PropertySource("classpath:redisConfig.properties")
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.pool.max-wait}")
private int maxWait;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Bean
public KeyGenerator wiselyKeyGenerator() {
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();
}
};
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout); //设置连接超时时间
factory.setPassword(password);
factory.getPoolConfig().setMaxIdle(maxIdle);
factory.getPoolConfig().setMinIdle(minIdle);
factory.getPoolConfig().setMaxTotal(maxActive);
factory.getPoolConfig().setMaxWaitMillis(maxWait);
return factory;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
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);
}
}
4、编写工具类PageHelperUtil、RedisUtils
分页工具
@Component
public class PageHelperUtil {
@Autowired
private RedisUtils redisUtil;
public PageInfo pageHelper(String redisKey, int pageNum) {
List pageList = redisUtil.lRange(redisKey, 0, -1);
PageInfo pageInfo = new PageInfo();
pageInfo.setTotal(pageList.size()); // 总量
pageInfo.setSize(4); // 每页条数
pageInfo.setPrePage(pageNum - 1 == 0 ? 1 : pageNum - 1); // 当前页
int pageNums = pageList.size() % 4 == 0 ? pageList.size() / 4 : Double.valueOf(pageList.size() / 4).intValue() + 1; // 总页数
pageInfo.setPageNum(pageNum); // 当前页
pageInfo.setPages(pageNums); // 总页数
pageInfo.setNextPage(pageNums == pageNum ? pageNums : pageNum + 1); // 下一页
if(pageNum==1){
pageInfo.setHasPreviousPage(false);
}else{
pageInfo.setHasPreviousPage(true);
}
if(pageNum==pageNums){
pageInfo.setHasNextPage(false);
}else{
pageInfo.setHasNextPage(true);
}
return pageInfo;
}
public List getPageHelperList(String redisKey,int pageNum) {
List list = redisUtil.lRange(redisKey, 4 * (pageNum - 1), (4 * pageNum ) - 1); // 当前页面显示条数 从pageSize * (pageNum - 1)条到 (pageSize * pageNum ) - 1条
return list;
}
}
Jedis工具类
@Service
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
public List<Object> lRange(String k, int l, int l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
5、改写controller层
@RequestMapping("/")
public String index(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, Model model) {
List<Article> articles = null;
if(redisUtils.exists("articles")){
System.out.println("in cash");
articles = pageHelperUtil.getPageHelperList("articles",pageNum);
}else{
articles = articleService.queryArticles();
for (Article article : articles) {
redisUtils.lPush("articles",article);
}
System.out.println("not in cash");
articles = pageHelperUtil.getPageHelperList("articles",pageNum);
}
PageInfo p = pageHelperUtil.pageHelper("articles", pageNum);
model.addAttribute("pageInfo",p);
model.addAttribute("articles",articles);
List<Category> categories = categoryService.allCategories();
model.addAttribute("types",categories);
model.addAttribute("count",articleService.countArt());
return "index";
}