pom.xml
<!-- spring 整合redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="cn.rjx.spring"></context:component-scan>
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> -->
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="3" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="true" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
<!-- ==============mybatis配置=========================================== -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:cn/rjx/spring/cache/dao/*Mapper.xml" />
</bean>
<!-- 配置扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描me.gacl.dao这个包以及它的子包下的所有映射接口类 -->
<property name="basePackage" value="cn.rjx.spring.cache.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- ==============mybatis事务配置=========================================== -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- redis配置 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.8.104"></property>
<property name="port" value="6379"></property>
<property name="database" value="2"></property>
<property name="usePool" value="true"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<property name="enableTransactionSupport" value="false"></property>
</bean>
<!-- 开启缓存注解扫描 -->
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg index="0" ref="redisTemplate"></constructor-arg>
</bean>
</beans>
注意:spring-data-redis 2.0.0及其以上org.springframework.data.redis.cache.RedisCacheManager的构造方法不在时template类型。这样注入会有错误。
缓存调用类:
@Service
//@CacheConfig(cacheNames="emp") 指定统一缓存名称
public class EmpServiceImpl implements EmpService{
@Autowired
EmpDao empDao;
@Override
//根据返回值emp来添加缓存,而不是根据参数,key:key值 value:缓存名 默认 value值~keys
@CachePut(key="#emp.id",value="emp")
public Emp addEmp(Emp emp) {
empDao.addEmp(emp);
return emp;
}
@Override
@CachePut(key="#emp.id",value="emp")
public Emp updateEmp(Emp emp) {
return emp;
}
@Override
@CacheEvict(key="#id",value="emp")
public void delEmp(String id) {
empDao.delEmp(id);
}
@Cacheable(key="#code",value="emp")
public Emp queryEmp(String code) {
return empDao.queryEmp(code);
}
}
@CachePut(key="#emp.id",value="emp") 取的是返回值中的数据,value是缓存的名字,这样可以实现缓存共用。key是存储在redis中的key名称。注解详细解释自己百度。
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:cn/rjx/spring/cache/bean1.xml"}) //加载配置文件
@Component
public class EmpTest {
Logger logger=LoggerFactory.getLogger("");
@Autowired
EmpService empService;
@Autowired
RedisUtils redisUtils;
@Test
public void test01(){
logger.info("------------------------------------------------------------------");
//redisUtils.putDataToCache("k1","v1");
Emp emps = empService.queryEmp("1001");
System.out.println(emps);
}
@Test
public void test02(){
logger.info("------------------------------------------------------------------");
Emp emp=new Emp();
emp.setId("1001");
emp.setName("wanger");
emp.setSalary(1);
empService.addEmp(emp);
}
@Test
public void test021(){
logger.info("------------------------------------------------------------------");
Emp emp=new Emp();
emp.setId("1001");
emp.setName("wangsi");
emp.setSalary(2000);
empService.updateEmp(emp);
}
@Test
public void test03(){
logger.info("------------------------------------------------------------------");
empService.delEmp("1001");;
}
}
缓存中如果有值会先从redis中获取:
使用@bean+@Configuration形式:
@Configuration
@EnableCaching //<cache:annotation-driven />
@PropertySource("classpath:cn/rjx/spring/cache/redis.properties")
public class CacheConfig /*extends CachingConfigurerSupport*/ {
@Autowired
private Environment env;
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
JedisConnectionFactory factory=new JedisConnectionFactory();
factory.setHostName(env.getRequiredProperty("redis.hostName"));
factory.setPort(Integer.valueOf(env.getRequiredProperty("redis.port")));
factory.setDatabase(Integer.valueOf(env.getRequiredProperty("redis.database")));
return factory;
}
@Bean
@SuppressWarnings("rawtypes")
public RedisTemplate redisTemplate(){
RedisTemplate template=new RedisTemplate();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new JdkSerializationRedisSerializer());
template.setEnableTransactionSupport(false);
return template;
}
@Bean
public RedisCacheManager cacheManager(RedisTemplate redisTemplate){
RedisCacheManager redisCacheManager=new RedisCacheManager(redisTemplate);
return redisCacheManager;
}
}
其中序列化方式比较可以参考:
http://blog.csdn.net/hotdust/article/details/51832926