构建基于Spring Boot 1.X应用,使用RedisCac
2019-10-30 本文已影响0人
菜的无法无天
构建基于Spring Boot 1.X应用,使用Cache
配置文件
pom配置文件
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.20.RELEASE</version>
</dependency>
redis配置文件redisContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!--jedis配置-->
<bean class="redis.clients.jedis.JedisPoolConfig" id="jedisPoolConfig">
<property name="maxIdle" value="50"/>
<property name="maxTotal" value="500"/>
<property name="maxWaitMillis" value="10000"/>
<property name="testOnBorrow" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="30000"/>
<property name="numTestsPerEvictionRun" value="100"/>
</bean>
<!--jedis仓库-->
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" id="jedisConnFactory">
<property name="poolConfig" ref="jedisPoolConfig"/>
<property name="hostName" value="${redis.host}"/>
<property name="password" value="${redis.password}"/>
<property name="port" value="${redis.port}"/>
<property name="timeout" value="10000"/>
</bean>
</beans>
springboot配置版文件
/**
* 连接redis的工厂类
* @return
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory =new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout);
factory.setPassword(password);
factory.setDatabase(database);
return factory;
}
@Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(50);
jedisPoolConfig.setMaxTotal(500);
jedisPoolConfig.setMaxWaitMillis(10000);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
jedisPoolConfig.setNumTestsPerEvictionRun(100);
return jedisPoolConfig;
}
缓存配置文件
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.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* ** spring redis缓存配置文件 **
* </p>
*
* @author douguohai
* @since 2019-04-28
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
/**
* 此方法为了避免分布式系统对某个类的hash数值不同导致不使用缓存而创建的
* 单机状态下,这个几乎无作用
*/
@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 CacheManager cacheManager(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate2) {
//获得redis缓存管理类
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate2);
// 开启使用缓存名称做为key前缀(这样所有同名缓存会整理在一起比较容易查找)
redisCacheManager.setUsePrefix(true);
//这里可以设置一个默认的过期时间 单位是秒
redisCacheManager.setDefaultExpiration(600L);
// 设置缓存的过期时间 单位是秒
Map<String, Long> expires = new HashMap<>();
//设置特定的缓存过期时间
expires.put("40l", 40L);
redisCacheManager.setExpires(expires);
return redisCacheManager;
}
@Bean(name = "redisTemplate2")
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//DefaultStrSerializer defaultStrSerializer=new DefaultStrSerializer();
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
使用方法
- 特定时间过期("40l是我在配置文件中配置过的"),他的生存周期只有40s
@Cacheable(value = "40l")
@Override
public PageObj getRepairShopInfoByPage(SearchRepairQuery searchRepairQuery) {
//无条件分页查询,按照订单总额排序
PageHelper.startPage(Integer.parseInt(searchRepairQuery.getPage()),Integer.parseInt(searchRepairQuery.getRows()));
PageInfo<ReapirShopVo> pageInfo=new PageInfo<ReapirShopVo>(xlcWeekMapper.getReapirShopInfo(searchRepairQuery));
//有时间区间按时间区间划分,然后订单总额排序
return Utils.PageInfo2PageObj(pageInfo);
}
- 默认过期时间
@Cacheable(value = "随便填写")
@Override
public PageObj getRepairShopInfoByPage(SearchRepairQuery searchRepairQuery) {
//无条件分页查询,按照订单总额排序
PageHelper.startPage(Integer.parseInt(searchRepairQuery.getPage()),Integer.parseInt(searchRepairQuery.getRows()));
PageInfo<ReapirShopVo> pageInfo=new PageInfo<ReapirShopVo>(xlcWeekMapper.getReapirShopInfo(searchRepairQuery));
//有时间区间按时间区间划分,然后订单总额排序
return Utils.PageInfo2PageObj(pageInfo);
}