redis與ssm整合方法(mybatis二級緩存)
SSM+redis整合
ssm框架之前已經(jīng)搭建過了,這里不再做代碼復制工作。
這里主要是利用redis去做mybatis的二級緩存,mybaits映射文件中所有的select都會刷新已有緩存,如果不存在就會新建緩存,所有的insert,update操作都會更新緩存。
redis的好處也顯而易見,可以使系統(tǒng)的數(shù)據(jù)訪問性能更高。本節(jié)只是展示了整合方法和效果,后面會補齊redis集群、負載均衡和session共享的文章。
下面就開始整合工作:
后臺首先啟動redis-server(后臺啟動與遠程連接linux服務的方法都需要改redis.conf文件),啟動命令“./src/redis-server ./redis.conf”
我這里是windows系統(tǒng)下開發(fā)的,推薦一個可視化工具“Redis Desktop manager”,需要遠程連接linux下的redis,需要linux下開啟端口對外開放(具體方法是修改/etc/sysconfig/iptables文件,增加對外端口開發(fā)命令)。
以上操作都完成后,即可遠程連接成功了,如圖:
現(xiàn)在還沒有緩存記錄,下面進入代碼階段,首先在pom.xml中增加需要的redis jar包
<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.6.2.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency> <!-- 添加druid連接池包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.24</version> </dependency>
pom.xml寫好后,還需要新增兩個配置文件:redis.properties
redis.host=192.168.0.109 redis.port=6379 redis.pass=123456 redis.maxIdle=200 redis.maxActive=1024 redis.maxWait=10000 redis.testOnBorrow=true
其中字段也都很好理解,再加入配置文件:spring-redis.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 連接池基本參數(shù)配置,類似數(shù)據(jù)庫連接池 --> <context:property-placeholder location="classpath*:redis.properties" /> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis.maxActive}"/> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!-- 連接池配置,類似數(shù)據(jù)庫連接池 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" > <property name="hostName" value="${redis.host}"></property> <property name="port" value="${redis.port}"></property> <property name="password" value="${redis.pass}"></property> <property name="poolConfig" ref="poolConfig"></property> </bean> <!-- 調(diào)用連接池工廠配置 --> <!-- <bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate"> <property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property> 如果不配置Serializer,那么存儲的時候智能使用String,如果用User類型存儲,那么會提示錯誤User can't cast to String?。?! <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> </bean> --> <bean id="redisCacheTransfer" class="com.cjl.util.RedisCacheTransfer"> <property name="jedisConnectionFactory" ref="jedisConnectionFactory" /> </bean> </beans>
配置文件寫好后,就開始java代碼的編寫:
JedisClusterFactory.java
package com.cjl.util; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean { private Resource addressConfig; private String addressKeyPrefix; private JedisCluster jedisCluster; private Integer timeout; private Integer maxRedirections; private GenericObjectPoolConfig genericObjectPoolConfig; private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$"); public JedisCluster getObject() throws Exception { return jedisCluster; } public Class<? extends JedisCluster> getObjectType() { return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); } public boolean isSingleton() { return true; } private Set<HostAndPort> parseHostAndPort() throws Exception { try { Properties prop = new Properties(); prop.load(this.addressConfig.getInputStream()); Set<HostAndPort> haps = new HashSet<HostAndPort>(); for (Object key : prop.keySet()) { if (!((String) key).startsWith(addressKeyPrefix)) { continue; } String val = (String) prop.get(key); boolean isIpPort = p.matcher(val).matches(); if (!isIpPort) { throw new IllegalArgumentException("ip 或 port 不合法"); } String[] ipAndPort = val.split(":"); HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1])); haps.add(hap); } return haps; } catch (IllegalArgumentException ex) { throw ex; } catch (Exception ex) { throw new Exception("解析 jedis 配置文件失敗", ex); } } public void afterPropertiesSet() throws Exception { Set<HostAndPort> haps = this.parseHostAndPort(); jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig); } public void setAddressConfig(Resource addressConfig) { this.addressConfig = addressConfig; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMaxRedirections(int maxRedirections) { this.maxRedirections = maxRedirections; } public void setAddressKeyPrefix(String addressKeyPrefix) { this.addressKeyPrefix = addressKeyPrefix; } public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { this.genericObjectPoolConfig = genericObjectPoolConfig; } }
RedisCache.java
package com.cjl.util; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.connection.jedis.JedisConnection; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import redis.clients.jedis.exceptions.JedisConnectionException; public class RedisCache implements Cache { private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private static JedisConnectionFactory jedisConnectionFactory; private final String id; private final ReadWriteLock rwl = new ReentrantReadWriteLock(); public RedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } logger.debug("MybatisRedisCache:id=" + id); this.id = id; } /** * 清空所有緩存 */ public void clear() { rwl.readLock().lock(); JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); connection.flushDb(); connection.flushAll(); } catch (JedisConnectionException e) { e.printStackTrace(); } finally { if (connection != null) { connection.close(); } rwl.readLock().unlock(); } } public String getId() { return this.id; } /** * 獲取緩存總數(shù)量 */ public int getSize() { int result = 0; JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); result = Integer.valueOf(connection.dbSize().toString()); logger.info("添加mybaits二級緩存數(shù)量:" + result); } catch (JedisConnectionException e) { e.printStackTrace(); } finally { if (connection != null) { connection.close(); } } return result; } public void putObject(Object key, Object value) { rwl.writeLock().lock(); JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); connection.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value)); logger.info("添加mybaits二級緩存key=" + key + ",value=" + value); } catch (JedisConnectionException e) { e.printStackTrace(); } finally { if (connection != null) { connection.close(); } rwl.writeLock().unlock(); } } public Object getObject(Object key) { // 先從緩存中去取數(shù)據(jù),先加上讀鎖 rwl.readLock().lock(); Object result = null; JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); result = serializer.deserialize(connection.get(serializer.serialize(key))); logger.info("命中mybaits二級緩存,value=" + result); } catch (JedisConnectionException e) { e.printStackTrace(); } finally { if (connection != null) { connection.close(); } rwl.readLock().unlock(); } return result; } public Object removeObject(Object key) { rwl.writeLock().lock(); JedisConnection connection = null; Object result = null; try { connection = jedisConnectionFactory.getConnection(); RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); result = connection.expire(serializer.serialize(key), 0); } catch (JedisConnectionException e) { e.printStackTrace(); } finally { if (connection != null) { connection.close(); } rwl.writeLock().unlock(); } return result; } public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) { RedisCache.jedisConnectionFactory = jedisConnectionFactory; } public ReadWriteLock getReadWriteLock() { // TODO Auto-generated method stub return rwl; } }
RedisCacheTransfer.java
package com.cjl.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; /** * 靜態(tài)注入中間類 */ public class RedisCacheTransfer { @Autowired public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) { RedisCache.setJedisConnectionFactory(jedisConnectionFactory); } }
SerializeUtil.java
package com.cjl.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * * @author cjl * */ public class SerializeUtil { /** * 序列化 */ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { // 序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { e.printStackTrace(); } return null; } /** *反序列化 */ public static Object unserialize(byte[] bytes) { if (bytes !=null) { ByteArrayInputStream bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } } return null; } }
所有東西準備齊全后還需要修改映射文件
要使mybaits緩存生效,還需如上圖這樣開啟二級緩存。配置文件還需要在web.xml中加載生效
一切準備就緒后,啟動服務
啟動成功后,點擊員工表單可以觸發(fā)查詢所有員工的方法,第一次進行查詢語句可以看到mybatis打印了查詢語句,并在redis服務器中更新了一條緩存
我們清空控制臺再次點擊查詢員工按鈕執(zhí)行查詢方法,可以看到?jīng)]有執(zhí)行查詢語句,證明第二次查詢直接從緩存中取值,沒有連接mysql進行查詢。
總結(jié)
以上所述是小編給大家介紹的redis與ssm整合方法(mybatis二級緩存),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Java同步鎖synchronized用法的最全總結(jié)
這篇文章主要介紹了Java同步鎖synchronized用法的最全總結(jié),需要的朋友可以參考下,文章詳細講解了Java同步鎖Synchronized的使用方法和需要注意的點,希望對你有所幫助2023-03-03使用java實現(xiàn)BBS論壇發(fā)送郵件過程詳解
這篇文章主要介紹了使用java發(fā)送郵件過程詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04spring boot 配置動態(tài)刷新實現(xiàn)詳解
這篇文章主要介紹了spring boot 配置動態(tài)刷新實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09SpringBoot實現(xiàn)接口等冪次校驗的示例代碼
本文主要介紹了SpringBoot實現(xiàn)接口等冪次校驗的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01