【SSM学习】Maven项目SSM框架整合Redis

下载安装Redis

官网下载:https://redis.io/download

Github下载:https://github.com/MicrosoftArchive/redis/releases

添加依赖包

在pom.xml中添加以下依赖包

<!-- spring-redis -->
<!-- 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>
<!-- mybaitis-redis整合-->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-redis</artifactId>
    <version>1.0.0-beta2</version>
</dependency>

添加redis配置文件

1.在applicationContext.xml中配置以下信息

<!--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>

<!--Redis连接池-->
<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.pass}"/>
        <property name="timeout" value="${redis.timout}"/>
        <property name="poolConfig" ref="poolConfig"/>
</bean>
<!--<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">-->
        <!--<property name="connectionFactory" ref="jedisConnectionFactory"/>-->
<!--</bean>-->
<!--使用中间类解决JedisConnectionFactory注入问题-->
<!--如果使用redis-mybatis整合包中的实现类,下面一条可以省略-->
<!--<bean id="redisCacheTransfer" class="cn.niconi.ssm.cache.RedisCache">-->
        <!--<constructor-arg value=""/>-->
        <!--<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>-->
<!--</bean>-->

2.添加redis.properties配置文件

redis.host=localhost
redis.port=6379
redis.pass=

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

实现中间类

中间类名与包名需要与上方xml中一致 如果使用整合包中的实现类这里可以忽略

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;

    /**
     * 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() {
        // TODO Auto-generated method stub
        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 void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCache.jedisConnectionFactory = jedisConnectionFactory;
    }
}

开启Mybatis缓存

在mybatis-config.xml配置文件中加入以下内容(注:mybatis-config.xml中,标记需要准寻一定顺序编写,否者会报错)

<settings>
    <!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
    <setting name="cacheEnabled" value="true"/>
    <!-- 查询时,关闭关联对象即时加载以提高性能 -->
    <setting name="lazyLoadingEnabled" value="false"/>
    <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
    <setting name="multipleResultSetsEnabled" value="true"/>
    <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
    <setting name="aggressiveLazyLoading" value="true"/>
</settings>

mapper中加入MyBatis二级缓存

在mapper.xml配置文件中加入以下内容
如果使用自己的实现类则加入

<cache type="包名.RedisCache"/>

如果使用整合包中的实现类则加入,需引入mybatis-redis包

<cache type="org.mybatis.caches.redis.RedisCache"/>
原文链接:,转发请注明来源!

发表评论

要发表评论,您必须先登录