关于spring cache 我们使用@Cacheable 配合@EnableCaching的方式 将属于缓存到如 ConcurrentMapCache 对象中,
整合Redis后我们将数据缓存到内存或者持久化到Redis数据库
一、配置
pom.xml
<!-- spring redis 整合 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<!-- jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency>
RedisCacheConfig
package com.learn.frame.redis.cache;
import java.lang.reflect.Method;
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.core.RedisTemplate;
//@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport{
/**
* 自定义产生key的方式
* @return
*/
/*@Bean
public KeyGenerator cacheKeyGenerator() {
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();
}
};
}*/
/**
* 缓存管理器
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
//return new RedisCacheManager(redisTemplate);
return new RedisCacheManager(redisTemplate,Arrays.asList(new String("redisCache"),new String("redisCache2")));
//注册名字为redisCache 和 redisCache2 的缓存
}
}
RedicCacheConfig 所做的是 注册 CacheManager 管理器,这里我们不需要相spring cache一样往CacheManager中添加所需Cache对象(封装了Map数据结构并用来存储缓存数据的对象),因为这里的cache由Redis(数据库)代替。
@EnableCaching 等价于xml中 <cache:annotation-driven/>
@Bean 等价于xml中 <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"/>
spring-redis.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.1.xsd">
<!-- redis config start -->
<!-- 配置JedisPoolConfig实例 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 配置JedisConnectionFactory -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value="${redis.password}" /> -->
<property name="database" value="${redis.dbIndex}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
</bean>
<!-- 配置RedisCacheConfig -->
<bean id="redisCacheConfig" class="com.learn.frame.redis.cache.RedisCacheConfig"/>
<!-- redis config end -->
</beans>
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
</bean>
<!-- 配置RedisCacheConfig -->
<bean id="redisCacheConfig" class="com.learn.frame.redis.cache.RedisCacheConfig"/>
<!-- redis config end -->
</beans>
RedisTemplate 的 Serializer 配置影响数据在Redis中的存储
redis.properties
#访问地址
redis.host=127.0.0.1
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留
redis.password=
#代表存储是从第0个开始
redis.dbIndex=0
redis.expiration=3000
#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制
redis.maxActive=600
#最大建立连接等待时间:单位ms。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
application.xml
基本配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.1.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:redis.properties"/>
<import resource="classpath:spring/spring-redis.xml" />
<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 使用@EnableCaching 方式代替如下xml-->
<!-- <cache:annotation-driven cache-manager="redisCacheManager" /> -->
</beans>
使用Mybatis处理jdbc
UserServiceImpl
package com.learn.frame.spring.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.learn.frame.spring.mapper.mysql.test.UserMapper;
import com.learn.frame.spring.po.User;
import com.learn.frame.spring.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
@Cacheable(value="redisCache",key="targetClass.getName()+'.'+methodName+'_'+args") //标注该方法查询的结果进入缓存,再次访问时直接读取缓存中的数据
public User searchUserById(int id) throws Exception {
System.out.println("Method executed..");
return userMapper.findUserById(id);
}
@Resource(name="userMapper")
//@Resource(type=UserMapper.class)
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
}
对searchUserById方法返回值进行缓存,cache名字为 redisCache ,
key值为 com.learn.frame.spring.service.impl.UserServiceImpl.searchUserById_args
三、Test测试
package com.learn.frame.redis;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.learn.frame.spring.po.User;
import com.learn.frame.spring.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext.xml"}) //加载配置文件
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Resource(name="userService")
private UserService userService;
@Test
public void test1() throws Exception{
User user = (User)userService.searchUserById(2);
System.out.println(user);
}
}
结果
使用RedisDeskTopManager工具 观察存储数据结构
用ZSET结构 来保存存储的key name为"缓存器名字~keys"
用STRING 来保存序列化的value(这里使用json序列化方式)