1. 程式人生 > >ssm+redis快取配置

ssm+redis快取配置

1、pom.xml引入一下jar

<!-- spring-redis實現 -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.6.2.RELEASE</version>
		</dependency>
		<!-- redis客戶端jar -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.8.0</version>
		</dependency>
		<!-- Ehcache實現,用於參考 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.0.0</version>
		</dependency>


2、application-context.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:context="http://www.springframework.org/schema/context"  
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans       
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
     http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
     http://www.springframework.org/schema/tx      
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd       
      http://www.springframework.org/schema/aop       
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd       
      http://www.springframework.org/schema/context       
      http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <!-- 資料來源定義 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <list>  
                <value>classpath:jdbc.properties</value>  
		<value>classpath:redis.properties</value>
            </list>  
        </property>  
    </bean>  
	
	<!-- redis資料來源 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxTotal" value="${redis.maxActive}" />
		<property name="maxWaitMillis" value="${redis.maxWait}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>
	<!-- Spring-redis連線池管理工廠 -->
	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
		p:pool-config-ref="poolConfig" />
	<!-- 使用中間類解決RedisCache.jedisConnectionFactory的靜態注入,從而使MyBatis實現第三方快取 -->
	<bean id="redisCacheTransfer" class="com.loan.security.cache.RedisCacheTransfer">
		<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
	</bean>
	
    <!-- 資料來源定義 -->  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${connection.driverClassName}" />  
        <property name="url" value="${connection.url}" />  
        <property name="username" value="${connection.username}" />  
        <property name="password" value="${connection.password}" />  
        <property name="maxActive" value="${connection.maxActive}" />  
        <property name="maxIdle" value="${connection.maxIdle}" />  
        <property name="minIdle" value="${connection.minIdle}" />  
        <property name="removeAbandoned" value="${connection.removeAbandoned}" />  
        <property name="removeAbandonedTimeout" value="${connection.removeAbandonedTimeout}" />  
        <property name="logAbandoned" value="${connection.logAbandoned}" />  
        <property name="defaultAutoCommit" value="${connection.defaultAutoCommit}" />  
        <property name="defaultReadOnly" value="${connection.defaultReadOnly}" />  
        <property name="validationQuery" value="${connection.validationQuery}" />  
        <property name="testOnBorrow" value="${connection.testOnBorrow}" />  
    </bean>  
    <!-- 建立sqlSessionFactory,同時指定資料來源 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  
        <property name="configLocation" value="classpath:mybatis-config.xml" />  
        <!-- 自動掃描mapper目錄, 省掉mybatis-config.xml裡的手工配置 -->  
        <property name="mapperLocations">  
            <list>  
                <!-- <value>classpath:com/loan/*/dao/xml/*.xml</value> -->  
                <value>classpath:com/loan/fore/dao/xml/*.xml</value>  
                <value>classpath:com/loan/back/dao/xml/*.xml</value>  
                <value>classpath:com/loan/security/dao/xml/*.xml</value>  
            </list>  
        </property>  
    </bean>  
    <!-- 通過掃描的模式,掃描目錄在com/loan/mapper目錄下 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.loan.*.dao.*" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  
    </bean>  
    <bean class="com.loan.util.SpringUtils" />  
    <!-- (事務管理) -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"></property>  
    </bean>  
    <!-- 使用annotation定義資料庫事務,這樣可以在類或方法中直接使用@Transactional註解來宣告事務 -->  
    <tx:annotation-driven transaction-manager="transactionManager" />  
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="search*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="approve" propagation="REQUIRED" />  
            <tx:method name="undo" propagation="REQUIRED" />  
            <tx:method name="*" propagation="SUPPORTS" read-only="true" />  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="serviceMethod"  
            expression="execution(* com.loan.*.service..*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />  
    </aop:config>  
    <!-- 自動搜尋註解路徑 -->  
    <context:component-scan base-package="com.loan"></context:component-scan>  
    <!-- 註冊定時器 -->  
    <bean id="timer"  
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean"  
        lazy-init="false" autowire="no">  
        <property name="triggers">  
            <list>  
                <ref bean="timerTaskTrigger" />  
            </list>  
        </property>  
    </bean>  
    <!-- 指定何時觸發定時任務 -->  
    <bean id="timerTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
        <property name="jobDetail">  
            <ref bean="timerTaskJobDetail" />  
        </property>  
        <property name="cronExpression">  
            <!-- 每天凌晨3點執行 -->  
            <value>0 0 3 * * ?</value>  
            <!-- <value>20 * * * * ?</value> -->  
        </property>  
    </bean>  
    <!-- 指定定時任務細節 呼叫哪個類 哪個方法 -->  
    <bean id="timerTaskJobDetail"  
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
        <property name="targetObject">  
            <ref bean="timerTaskInstance" />  
        </property>  
        <property name="targetMethod">  
            <value>doTask</value>  
        </property>  
        <property name="concurrent" value="false" />  
    </bean>  
    <!-- 例項化定時任務類 -->  
    <bean id="timerTaskInstance" class="com.loan.security.plug.TimerTask"></bean>  
</beans>

3、redis.properties
# Redis settings  
redis.host=192.168.100.161
redis.port=6379  
redis.pass=root

redis.maxIdle=300  
redis.maxActive=600  
redis.maxWait=1000  
redis.testOnBorrow=true 

4、RedisCacheTransfer.java
package com.loan.security.cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

/**
 * 
 * @描述: 靜態注入中間類
 * @版權: Copyright (c) 2016 
 * @作者: xiad
 * @版本: 1.0 
 * @建立日期: 2016年3月2日 
 * @建立時間: 下午8:02:57
 */
public class RedisCacheTransfer 
{

    @Autowired
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }

}
5、RedisCache.java
package com.loan.security.cache;

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;

/**
 * 
 * @描述: 使用第三方記憶體資料庫Redis作為二級快取
 * @版權: Copyright (c) 2016 
 * @作者: xiad
 * @版本: 1.0 
 * @建立日期: 2016年3月2日 
 * @建立時間: 下午8:02:57
 */
public class RedisCache implements Cache
{
    private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;

    /**
     * The {@code ReadWriteLock}.
     */
    private final ReadWriteLock readWriteLock = 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;
    }

    @Override
    public void clear()
    {
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.flushDb();
            connection.flushAll();
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public String getId()
    {
        return this.id;
    }

    @Override
    public Object getObject(Object key)
    {
        Object result = null;
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    @Override
    public ReadWriteLock getReadWriteLock()
    {
        return this.readWriteLock;
    }

    @Override
    public int getSize()
    {
        int result = 0;
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            result = Integer.valueOf(connection.dbSize().toString());
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    @Override
    public void putObject(Object key, Object value)
    {
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public Object removeObject(Object key)
    {
        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();
            }
        }
        return result;
    }

    public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCache.jedisConnectionFactory = jedisConnectionFactory;
    }

}

6、mapper.xml中引入Redis快取
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.loan.security.dao.mapper.DictionaryCatalogMapper">
<cache type="com.loan.security.cache.RedisCache"/>
</mapper>