基spring cache 整合redis

来源:互联网 发布:淘宝上尺码是什么意思 编辑:程序博客网 时间:2024/06/05 13:32

先把整合,需要配置的步骤,写下来。

1.配置 连接池    核心类JedisPoolConfig

2.配置 连接工厂   核心类JedisCoonectionFactory

3.配置 序列化类型 核心类StringRedisSerializer

4.配置Redis核心操作类  RedisTemplate

5.配置 基于spring cache的redisCacheManager  核心类RedisCacheManager



<!-- 配置连接池 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大允许,有多少个状态为 Idle的Jedis空闲实例 默认为8 -->
<property name="maxIdle" value="100" />
<!-- 最大连接数 -->
<property name="maxTotal" value="15" />
<!-- 最大等待时间 (根据jedis jar包版本不同 ,这个属性也是不同的,低版本为 MAX_WAIT ) -->
<property name="maxWaitMillis" value="10000" />
<!-- 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 -->
<property name="testOnBorrow" value="true" />
</bean>

<!-- Redis的连接工厂 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- 连接地址 我的是本机上的redis -->
<property name="hostName" value="127.0.0.1" />
<!-- 连接密码 redis默认是没有密码的 没有直接 "" -->
<property name="password" value="106310" />
<!-- redis端口 默认6379 -->
<property name="port" value="6379" />
<!-- 引用连接池 -->
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>

<!-- 序列化 key (保证存入redis 的key 不乱码) -->
<bean id="stringRedisSerializer"
class="org.springframework.data.redis.serializer.StringRedisSerializer">
</bean>

<!-- 操作redis核心类 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<!-- 引入redis工厂 -->
<property name="connectionFactory" ref="connectionFactory" />
<!-- 引入 spring Key的序列化(还可以设置 hashKey,这里举例,简单起见只插入spring 的键值对) -->
<property name="keySerializer" ref="stringRedisSerializer" />
</bean>

<!-- 基于spring cache的redisCacheManager -->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:template-ref="redisTemplate" />


基于spring-mybatis写一个简单的查询和插入,这里就不多说了,直接看Service层代码

查询操作:

其中Cacheable注解 先查询缓存中有没有 该key的值,没有查询数据库,并将该方法的返回值结果保存到缓存中。

属性:key  Redis键值对 中的key 读取缓存时使用(该属性不是必须的,key会自动生成)

属性:value  将生成的键保存到那个cache中(因为我们是在Redis操作的,键都是唯一的,所以这里的value就显得多余了,不过是必须得填写的)

CacheAble  CachePut  CacheEvict用法: http://blog.csdn.net/u014381863/article/details/48788199

springEl表达式生成key策略:http://blog.csdn.net/fireofjava/article/details/48913335

 @Cacheable(key = "#user1.id",value="user")
 @Override
 public User login(User user1) {
  List<User> list = dao.select(user1);
  return list.get(0);
 }


测试:先去缓存中查找(redis),没有则查数据库,并将结果保存到Redis中

1.首先将数据库中手动插入一条信息 ID=1 username="张三" password="123456";

2.运行测试代码

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService bean = app.getBean(UserService.class);

User user = new User();
  user.setId("1");
  User login = bean.login(user);
  System.out.println(login);

输入结果:1 张三 123456


3.然后去查看 redis 在控制台输入 get 1   有值说明,已经保存到了Redis中了。

4.然后删除数据库中的信息,在运行查询的例子。

依然输出 :1 张三 123456 

说明第二此查询是从redis中查询的。














原创粉丝点击