1.pom引入依赖
redis.clients
jedis
2.9.0
org.springframework.data
spring-data-redis
2.0.5.RELEASE
2.新增配置文件 redis-config.properties
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
maxWait:连接池中连接用完时,新的请求等待时间,毫秒
maxIdle: 最大闲置个数
3.新增spring配置文件applicationContext-redis.xml
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/beans/spring-cache.xsd">
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
4.创建枚举用于存放
package com.qingcheng.utlis;
public enum CacheKey {
AD,//广告
SKU_PRICE,//价格
CATEGORY_TREE;//商品分类导航树
}
5.注入redisTemplate使用,此处使用的存入枚举,当然也可以用其他的
redisTemplate.boundValueOps(CacheKey.CATEGORY_TREE).set(categoryTree);
6.启动项目初始化的类调用,当项目启动会自动执行这个方法
@Component
public class Init implements InitializingBean {
@Autowired
private AdService adService;
public void afterPropertiesSet() throws Exception {
System.out.println("缓存预热");
adService.positions();
}
}