SSM框架下的redis缓存

时间:2022-08-14 16:33:34

基本SSM框架搭建:http://www.cnblogs.com/fuchuanzhipan1209/p/6274358.html

配置文件部分:

第一步:加入jar包

pom.xml

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

主配置文件:applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p
="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc
="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop
="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "
>

<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<!-- 引入数据库配置文件 -->
<bean id="propertyConfigurer"
class
="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.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.nuo.cache.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- 配置数据源 ,dbcp -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method
="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="com.nuo.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

<!-- service -->
<bean id="PersonService" class="com.nuo.service.impl.PersonServiceImpl" />


<!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 -->
<bean id="transactionManager"
class
="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 dataSource在applicationContext-dao.xml中配置了 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut
="execution(* com.nuo.service.impl.*.*(..))" />
</aop:config>

</beans>

mybitas配置文件:

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"
>
<configuration>

<!-- 全局setting配置,根据需要添加 -->



<!-- 配置mapper 由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。 必须遵循:mapper.xml和mapper.java文件同名且在一个目录 -->

<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
<settings>

<!-- 全局映射器启用缓存 *主要将此属性设置完成即可 -->
<setting name="cacheEnabled" value="true" />

<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="false" />

<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true" />

<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="true" />

</settings>
<!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="com.nuo.model" />
</typeAliases>

<!-- <mappers> </mappers> -->
</configuration>

redis配置:

redis.properties

# Redis settings  
redis.host=127.0.0.1
redis.port=6379
redis.pass=

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

 Java代码工具类部分

静态注入中间类

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);

}

}

第三方内存数据库Redis

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
* @作者:
* @版本: 1.0
* @创建日期:
* @创建时间:
*/
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 static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.jedisConnectionFactory
= jedisConnectionFactory;
}

}

Java代码 SQL语句部分

<?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.nuo.mapper.PersonMapper">
<cache eviction="LRU" type="com.nuo.cache.RedisCache" />
<resultMap type="Person" id="PersonMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="gender" property="gender"/>
</resultMap>
<select id="getByName" parameterType="String" resultMap="PersonMap">
<![CDATA[
SELECT
*
FROM
person
WHERE
name = LOWER(#{name})
]]>
</select>

<insert id="addPerson" parameterType="Person">
<![CDATA[
insert into
person(name,gender)
values(#{name},#{gender});

]]>
</insert>

<select id="getById" parameterType="int" resultMap="PersonMap">
<![CDATA[
SELECT
*
FROM
person
WHERE
id = LOWER(#{id})
]]>
</select>

</mapper>

关键部分:

 <cache eviction="LRU" type="com.nuo.cache.RedisCache" />

执行验证

第一次执行sql查询:

SSM框架下的redis缓存

第二次执行相同语句时,不再打印sql语句,说明直接从缓存中读取了数据。

SSM框架下的redis缓存

 redis服务器查看

SSM框架下的redis缓存