在SSM中使用redis作service層快取和MyBatis二級快取
redis在windows端使用 下載壓縮包後解壓雙擊redis-server.exe或在目錄下開啟命令列視窗輸入redis-server.exe redis.windows.conf執行redis redis客戶端分為自帶的命令框和視覺化工具 自帶的命令框雙擊reids-cli.exe(沒有設定密碼的情況下)或在目錄下開啟命令列視窗輸入redis-cli.exe -h localhost -p 6379執行redis客戶端 視覺化工具使用redisDesktopManager 一些redis簡單的命令 檢視密碼 config get requirepass 設定密碼config set requirepass “root” 這種方式設定後重啟redis密碼失效,永久的方式是去redis.window.conf檔案中去找到requirepass修改,設定密碼後啟動客戶端要加上-a root 設值 set key value 取值get key 檢視所有鍵keys * 檢視鍵數量dbsize 切換資料庫select index 清空當前資料庫flushdb 清空所有資料庫fulushall
service層做快取 pom檔案中引入
<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.6.RELEASE</version> </dependency>
applicationContext.xml配置
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis.pool.maxTotal}"/> <property name="maxIdle" value="${redis.pool.maxIdle}"/> <property name="minIdle" value="${redis.pool.minIdle}"/> <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/> <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/> <property name="testOnReturn" value="${redis.pool.testOnReturn}"/> <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/> </bean> <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="timeout" value="${redis.timeout}"/> <property name="poolConfig" ref="jedisPoolConfig"/> <!--使用連線池預設true--> <property name="usePool" value="true" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <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="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name="connectionFactory" ref="jedisConnectionFactory"/> </bean> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg index="0" ref="redisTemplate"/> <property name="defaultExpiration" value="${redis.cacheExpire}" /> </bean> <!-- 啟用快取註解功能--> <cache:annotation-driven cache-manager="cacheManager" />
service層
//清空user下快取
//@CacheEvict(value = "user", allEntries = true)
@Override
public int insert(User user) {
return userMapper.insert(user);
}
//@Cacheable(value = "user", key = "'selectByName('+#name+')'")
@Override
public User selectByName(String name) {
return userMapper.selectByName(name);
}
//@Cacheable(value = "user", key = "'selectAll'")
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
理解幾個註釋@CachePut不去檢查快取中是否存在,直接去資料庫中取並放入快取中 <cache:annotation-driven cache-manager=“cacheManager” /> mode屬性可選值由proxy和aspectj,預設是proxy,當mode為proxy時,只有快取方法在外部呼叫時Spring Cache 才會發生作用,並且只有Public方法上標註@Cacheable等標註才會起作用,當mode為aspectj時不存在上面兩個問題 proxy-target-class屬性表示是否代理class,預設是false,@Cacheable等可以標註在介面方法上,這對於基於 介面代理沒有問題,當proxy-target-class為true或mode為aspectj時是基於class進行操作的,定義在介面上的註解不會識別的 參考https://www.cnblogs.com/fashflying/p/6908028.html
MyBatis二級快取 applicationContext.xml檔案中新增
<bean class="org.example.redis.MybatisRedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>
建立MybatisRedisCacheTransfer類和MybatisRedisCache 這些key儲存在redis的list結構,以id作為list的key,每個mapper介面產生的id不變 參考https://www.jianshu.com/p/1d0be9bf3f80 Mapper.xml中新增
<cache type="org.example.redis.MybatisRedisCache"/>
<!--#{name}自動加引號,預處理防止SQL注入 ${column}不加引號用於order by-->
<select id="selectByName" resultType="User" useCache="true">
select id, user_name, user_password, user_email, create_time
from user
where user_name=#{name}
</select>
<insert id="insert" flushCache="true">
insert into user(user_name, user_password, user_email)
value(#{userName}, #{userPassword}, #{userEmail})
</insert>
<select id="selectAll" resultMap="BaseResultMap" useCache="true">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select id, user_name, user_password, user_email, create_time
from user
</select>
Mybatis二級快取useCache=true這個查詢sql的結果進行快取,其餘insert update delete可以flushCache=true會把 redis中該mapper下的二級快取清除 參照https://www.jianshu.com/p/52b0805f1950