一,引入jar包
<!-- jedis依赖包 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- redis数据依赖包 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.11.RELEASE</version>
</dependency>
二.redis.properties配置文件
maxIdle=30
minIdle=10
maxTotal=50
url=192.168.232.130
port=6379
password=123@456
三.redis.xml
<?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:cache="http://www.springframework.org/schema/cache"
xmlns:uti="http://www.springframework.org/schema/util"
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/cache/spring-cache.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 开启spring缓存注解 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<uti:properties id="pros" location="classpath:redis.properties"/>
<!-- 配置jedis连接池 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="#{pros.maxIdle}"></property>
<property name="minIdle" value="#{pros.minIdle}"></property>
<property name="maxTotal" value="#{pros.maxTotal}"></property>
</bean>
<!-- 配置jedis连接工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="#{pros.url}"></property>
<property name="port" value="#{pros.port}"></property>
<property name="poolConfig" ref="jedisPoolConfig"></property>
<property name="password" value="#{pros.password}"/>
</bean>
<!-- 配置jedis模板 -->
<bean id="jedisTemplate" 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="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<property name="enableTransactionSupport" value="true"></property>
</bean>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="jedisTemplate"/>
</bean>
</beans>
四.添加注解
@Cacheable(value = "cacheManager",key = "'room_total'")
public int getTotal() {
System.out.println("getTotal");
return roomMapper.selectByExample(new RoomExample()).size();
}