基本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查询:

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

redis服务器查看

SSM框架下的redis缓存的更多相关文章

  1. java配置SSM框架下的redis缓存

    pom.xml引入依赖包 <!--jedis.jar --> <dependency> <groupId>redis.clients</groupId> ...

  2. 关于在SSM框架下使用PageHelper

    首先,如果各位在这块配置和代码有什么问题欢迎说出来,我也会尽自己最大的能力帮大家解答 这些代码我都是写在一个小项目里的,项目的github地址为:https://github.com/Albert-B ...

  3. ssm框架下怎么批量删除数据?

    ssm框架下批量删除怎么删除? 1.单击删除按钮选中选项后,跳转到js函数,由函数处理 2. 主要就是前端的操作 js 操作(如何全选?如何把选中的数据传到Controller中) 3.fun()函数 ...

  4. Yii框架下使用redis做缓存,读写分离

    Yii框架中内置好几个缓存类,其中有memcache的类,但是没有redis缓存类,由于项目中需要做主从架构,所以扩展了一下: /** * FileName:RedisCluster * 配置说明 * ...

  5. Windows环境下使用Redis缓存工具的图文详细方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...

  6. Jquery DataTable AJAX跨域请求的解决方法及SSM框架下服务器端返回JSON格式数据的解决方法

    如题,用HBuilder开发APP,涉及到用AJAX跨域请求后台数据,刚接触,费了不少时间.幸得高手指点,得以解决. APP需要用TABLE来显示数据,因此采用了JQ 的DataTable.  在实现 ...

  7. SSM框架下分页的实现(封装page.java和List<?>)

    之前写过一篇博客  java分页的实现(后台工具类和前台jsp页面),介绍了分页的原理. 今天整合了Spring和SpringMVC和MyBatis,做了增删改查和分页,之前的逻辑都写在了Servle ...

  8. ssm框架下实现文件上传

      1.由于ssm框架是使用Maven进行管理的,文件上传所需要的jar包利用pom.xml进行添加,如下所示: <properties> <commons-fileupload.v ...

  9. yii框架下使用redis

    1 首先获取到 yii2-redis-master.zip 压缩包 下载地址https://github.com/yiisoft/yii2-redis/archive/master.zip 2 把下载 ...

随机推荐

  1. flask_mysql入库

    mysql 的入库和MongoDB的有一点点的区别 不过都很重要,都必须要掌握的技能, 现在我来演示一下mysql入库的过程: 首先  我们要导包,这是必不可少的一部分,都不用我说了吧 #导报 imp ...

  2. 在Ubuntu下编译安装nginx

    一.安装nginx 1.安装前提 a)epoll,linux内核版本为2.6或者以上 b)gcc编译器,g++编译器 c)pcre库,函数库,支持解析正则表达式 d)zlib库:压缩解压功能 e)op ...

  3. div在页面垂直居中方法---增强改进版

    div在页面垂直居中方法---改进版 .wrap{ background: #ffffff; position:absolute; margin:auto; top:; bottom:; left:; ...

  4. (转载)elasticsearch 查询(match和term)

    原文地址:https://www.cnblogs.com/yjf512/p/4897294.html elasticsearch 查询(match和term) es中的查询请求有两种方式,一种是简易版 ...

  5. jQuery ajax请求错误返回status 0和错误error的问题

    上周发现一个jQuery ajax请求错误返回status 0和错误error的问题,responseText是"error",状态码是0而不是200: $.ajax({ type ...

  6. Chrome 开发工具之Timeline/Performance

    之前有说到Element,Console,Sources大多运用于debug,Network可用于debug和查看性能,今天的主角Timeline(现已更名Performance)更多的是用在性能优化 ...

  7. 百度&高德地图小区景点边界轮廓实现

    经常的我们在使用地图功能时,会发现在选择一个小区或者一个热门景点的时候,地图上面会给出其边界轮廓,能够方便我们知道其范围大小,有时候在我们使用地图组件的时候,也会面临着类似的需求.比如在地图上面标识出 ...

  8. kafka 日志结构

    1.kafka日志结构 直接举例子: 例如kafka有个名字叫 haha 的topic,那么kafka日志下面有kafka-0,kafka-1,kafka-2...,kafka-n,具体多少个,创建分 ...

  9. CentOS 7下搭配简单的C语言开发环境

    在CentOS 7下安装gcc,gcc是编译和运行C语言的工具, 安装命令: yum install gcc 中途如果有询问则输入y 安装成功后,通过以下命令 gcc --version 来查看安装的 ...

  10. java中 immutable,future,nio

    什么是Future? 用过Java并发包的朋友或许对Future (interface) 已经比较熟悉了,其实Future 本身是一种被广泛运用的并发设计模式,可在很大程度上简化需要数据流同步的并发应 ...