[Redis]spring-data-redis Spring 整合 redis 做 cache xml实现

Spring整合redis做缓存

1. 导包


org.springframework.dataspring-data-redis1.6.2.RELEASE

redis.clientsjedis2.9.0


com.fasterxml.jackson.corejackson-core2.9.2


com.fasterxml.jackson.corejackson-databind2.9.2


com.fasterxml.jackson.corejackson-annotations2.9.2


commons-loggingcommons-logging1.2


log4jlog4j1.2.17

 

2. redis.properties文件

#============================#
#==== Redis settings ====#
#============================#
#redis 服务器 IP
redis.host=127.0.0.1
#redis 服务器端口
redis.port=6379
#redis 密码
redis.pass=
#redis 支持16个数据库(相当于不同用户)可以使不同的应用程序数据彼此分开同时又存储在相同的实例上
redis.dbIndex=1
#redis 缓存数据过期时间单位秒
redis.expiration=3000
#控制一个 pool 最多有多少个状态为 idle 的jedis实例
redis.maxIdle=300
#控制一个 pool 可分配多少个jedis实例
redis.maxActive=600
#当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true

3. 配置spring-cache-redis.xml文件


4. 开启缓存, 并配置key生成策略

package com.learn.cache;import java.lang.reflect.Method;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {protected final static Logger log = LoggerFactory.getLogger(RedisCacheConfig.class);private volatile JedisConnectionFactory mJedisConnectionFactory;private volatile RedisTemplate mRedisTemplate;private volatile RedisCacheManager mRedisCacheManager;public RedisCacheConfig() {super();}public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate mRedisTemplate, RedisCacheManager mRedisCacheManager) {super();this.mJedisConnectionFactory = mJedisConnectionFactory;this.mRedisTemplate = mRedisTemplate;this.mRedisCacheManager = mRedisCacheManager;}public JedisConnectionFactory redisConnectionFactory() {return mJedisConnectionFactory;}public RedisTemplate redisTemplate(RedisConnectionFactory cf) {return mRedisTemplate;}public CacheManager cacheManager(RedisTemplate redisTemplate) {return mRedisCacheManager;}@Bean@Overridepublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method,Object... params) {//规定  本类名+方法名+参数名 为keyStringBuilder sb = new StringBuilder();sb.append(target.getClass().getName() + "_");sb.append(method.getName() + "_");for (Object obj : params) {sb.append(obj.toString() + ",");}return sb.toString();}};}}

5. 编写实体类, 及cache使用方法

package com.learn.cache.model;import java.io.Serializable;/*** 首先定义一个实体类:账号类,具备基本的 id 和 name 属性,且具备 getter 和 setter 方法** 清单 1. Account.java** @author qq* @date 2018-04-27*/
public class Account implements Serializable {private static final long serialVersionUID = 1L;private int id;private String name;private String password;public Account() {super();}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Account(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", password='" + password + '\'' +'}';}
}
package com.learn.cache.service;import com.learn.cache.model.Account;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;/*** 使用@Cacheable, @CachePut, @CacheEvict, @CacheConfig spring通过AOP对方法进行缓存管理* 

* 实体类就是上面自定义缓存方案定义的 Account.java,这里重新定义了服务类,如下:*

* 清单 6. AccountService.java** @author aa* @date 2018-04-27*/ public class TestService {@Cacheable(value = "redis-cache-string", key = "'redis_key_' + #userName", condition = "true")public String getResisValue(String userName) {// 方法内部实现不考虑缓存逻辑,直接实现业务System.out.println("查询数据库..." + userName);return "redis_value_" + userName;}// @CacheEvict(value = "redis-cache-string", key = "'redis_key' + #userName", condition = "true", allEntries = true, beforeInvocation = true)@CacheEvict(value = "redis-cache-string", key = "'redis_key_' + #userName", condition = "true")public void delRedisValue(String userName) {System.out.println("删除数据库");} }

package com.learn.cache.service;import com.learn.cache.model.Account;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;/*** 使用@Cacheable, @CachePut, @CacheEvict, @CacheConfig spring通过AOP对方法进行缓存管理* 

* 实体类就是上面自定义缓存方案定义的 Account.java,这里重新定义了服务类,如下:*

* 清单 6. AccountService.java** @author aa* @date 2018-04-27*/ public class AccountService {/*** 使用了一个缓存名叫 accountCache** 注意,此类的 getAccountByName 方法上有一个注释 annotation,即 @Cacheable(value=”accountCache”),* 这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。* 这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。** key condition ,前面的 # 号代表这是一个 SpEL 表达式* @param userName* @return*/@Cacheable(value = "accountCache", key = "'model:' + #userName", condition = "#userName.length() >= 4")public Account getAccountByName(String userName) { // Jackson2JsonRedisSerializer json = new Jackson2JsonRedisSerializer();// 方法内部实现不考虑缓存逻辑,直接实现业务return getFromDB(userName);}@Cacheable(value = "accountCache", key = "#userName.concat(#password)")public Account getAccount(String userName, String password, boolean sendLog) {// 方法内部实现不考虑缓存逻辑,直接实现业务return getFromDB(userName, password);}/*** 好,到目前为止,我们的 spring cache 缓存程序已经运行成功了,但是还不完美,* 因为还缺少一个重要的缓存管理逻辑:清空缓存,当账号数据发生变更,那么必须要清空某个缓存,另外还需要定期的清空所有缓存,以保证缓存数据的可靠性。* 清空 accountCache 缓存** 清单 10. AccountService.java* @param account*/ // @CacheEvict(value = "accountCache", key = "#account.getName()")/*** 更新 accountCache 缓存* @param account dd*/@CachePut(value = "accountCache", key = "#account.getName()")public void updateAccount(Account account) {updateDB(account);}/*** reload 清空 accountCache 缓存*/@CacheEvict(value = "accountCache", allEntries = true)public void reload() {}private Account getFromDB(String acctName) {System.out.println("real querying db..." + acctName);return new Account(acctName);}private Account getFromDB(String acctName, String password) {System.out.println("real querying db..." + acctName + "+" + password);return new Account(acctName);}private void updateDB(Account account) {System.out.println("real update db..." + account.getName());}}

 

6. 测试字符串存储及实体类存储

package com.learn.cache;import com.learn.cache.model.Account;
import com.learn.cache.service.AccountService;
import com.learn.cache.service.TestService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;public class Main {public static void main(String[] args) {// 加载 spring 配置文件ApplicationContext context = new ClassPathXmlApplicationContext("spring-cache-redis.xml");RedisTemplate redisTemplate = (RedisTemplate) context.getBean("redisTemplate");redisTemplate.opsForValue().set("redis2", "ceshiRedis222");System.out.println(redisTemplate.opsForValue().get("redis2"));// 测试string类型缓存
//        testRedisCache(context);
//        delRedisCache(context);// 测试json类型缓存testRedisCacheModel(context);}/*** 测试普通村缓存* @param context*/public static void testRedisCache(ApplicationContext context) {// 测试缓存TestService s = (TestService) context.getBean("testServiceBean");// 第一次查询,应该走数据库System.out.print("first query...");s.getResisValue("somebody");// 第二次查询,应该不查数据库,直接返回缓存的值System.out.print("second query...");s.getResisValue("somebody");System.out.println();}/*** 测试实体类缓存* @param context 文档*/public static void testRedisCacheModel(ApplicationContext context) {// 测试缓存AccountService s = (AccountService) context.getBean("accountServiceBean");// 第一次查询,应该走数据库System.out.println("first query...");s.getAccountByName("somebody");// 第二次查询,应该不查数据库,直接返回缓存的值System.out.println("second query...");Account account = s.getAccountByName("somebody");System.out.println(account);}/*** 删除缓存* @param context 文档*/public static void delRedisCache(ApplicationContext context) {// 测试缓存TestService s = (TestService) context.getBean("testServiceBean");// 第一次查询,应该走数据库System.out.print("first query...");s.getResisValue("somebody");// 第二次查询,应该不查数据库,直接返回缓存的值System.out.println("second query...");String jj = s.getResisValue("somebody");System.out.println(jj + ";second query end...");System.out.println("clear cache begin...");s.delRedisValue("somebody");System.out.println("three query...");s.getResisValue("somebody");}
}

 

报错看 https://mp.csdn.net/postedit/80170626

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部