SSM+redis整合
ssm框架之前已經搭建過了,這裡不再做代碼複製工作。
這裡主要是利用redis去做mybatis的二級緩存,mybaits映射文件中所有的select都會刷新已有緩存,如果不存在就會新建緩存,所有的insert,update操作都會更新緩存。
redis的好處也顯而易見,可以使系統的數據訪問性能更高。本節只是展示了整合方法和效果,後面會補齊redis集群、負載均衡和session共享的文章。
下面就開始整合工作:
後台首先啟動redis-server(後台啟動與遠程連接linux服務的方法都需要改redis.conf文件),啟動命令“./src/redis-server ./redis.conf”
我這裡是windows系統下開發的,推荐一個可視化工具“Redis Desktop manager”,需要遠程連接linux下的redis,需要linux下開啟端口對外開放(具體方法是修改/etc/sysconfig/iptables文件,增加對外端口開發命令)。
以上操作都完成後,即可遠程連接成功了,如圖:
現在還沒有緩存記錄,下面進入代碼階段,首先在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.109redis.port=6379redis.pass=123456redis.maxIdle=200redis.maxActive=1024redis.maxWait=10000redis.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"> <!-- 連接池基本參數配置,類似數據庫連接池--> <context:property-placeholder location="classpath*:redis.properties" /> <bean id="poolConfig"> <property name="maxTotal" value="${redis.maxActive}"/> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!-- 連接池配置,類似數據庫連接池--> <bean id="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> <!-- 調用連接池工廠配置--> <!-- <bean id="redisTemplate"> <property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property> 如果不配置Serializer,那麼存儲的時候智能使用String,如果用User類型存儲,那麼會提示錯誤User can't cast to String! ! ! <property name="keySerializer"> <bean /> </property> <property name="valueSerializer"> <bean /> </property> </bean> --> <bean id="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; } /** * 獲取緩存總數量*/ public int getSize() { int result = 0; JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); result = Integer.valueOf(connection.dbSize().toString()); logger.info("添加mybaits二級緩存數量:" + 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) { // 先從緩存中去取數據,先加上讀鎖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;/** * 靜態注入中間類*/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中加載生效
一切準備就緒後,啟動服務
啟動成功後,點擊員工表單可以觸發查詢所有員工的方法,第一次進行查詢語句可以看到mybatis打印了查詢語句,並在redis服務器中更新了一條緩存
我們清空控制台再次點擊查詢員工按鈕執行查詢方法,可以看到沒有執行查詢語句,證明第二次查詢直接從緩存中取值,沒有連接mysql進行查詢。
總結
以上所述是小編給大家介紹的redis與ssm整合方法(mybatis二級緩存),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!