redis作为mybatis的二级缓存

redis作为二级缓存服务器,来替代mybatis的二级缓存,至于二级缓存有什么缺点我想大家都懂吧,

[service] 2016-08-31 21:01:32,912 - com.erp.dao.TestMybatisMapper.selectByPrimaryKey -19446 [http-nio-8080-exec-6] DEBUG com.erp.dao.TestMybatisMapper.selectByPrimaryKey  - ==>  Preparing: select TID, TNAME from TESTMYBATIS where TID = ? 
    [service] 2016-08-31 21:01:32,912 - com.erp.dao.TestMybatisMapper.selectByPrimaryKey -19446 [http-nio-8080-exec-6] DEBUG com.erp.dao.TestMybatisMapper.selectByPrimaryKey  - ==> Parameters: 6(BigDecimal)
    [service] 2016-08-31 21:01:32,944 - com.erp.dao.TestMybatisMapper.selectByPrimaryKey -19478 [http-nio-8080-exec-6] DEBUG com.erp.dao.TestMybatisMapper.selectByPrimaryKey  - <==      Total: 1
    [service] 2016-08-31 21:01:32,945 - com.erp.utils.redcache.RedisCache -19479 [http-nio-8080-exec-6] DEBUG com.erp.utils.redcache.RedisCache  - >>>>>>>>>>>>>>>>>>>>>>>>putObject:1716629384:864926724:com.erp.dao.TestMybatisMapper.selectByPrimaryKey:0:2147483647:select 
     
    TID, TNAME
   
    from TESTMYBATIS
    where TID = ?:6=[TestMybatis [tid=6, tname=asd]]
    [service] 2016-08-31 21:01:32,946 - org.mybatis.spring.SqlSessionUtils -19480 [http-nio-8080-exec-6] DEBUG org.mybatis.spring.SqlSessionUtils  - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a766442]
    [service] 2016-08-31 21:01:32,946 - org.springframework.jdbc.datasource.DataSourceUtils -19480 [http-nio-8080-exec-6] DEBUG org.springframework.jdbc.datasource.DataSourceUtils  - Returning JDBC Connection to DataSource
    TestMybatis [tid=6, tname=asd]
[service] 2016-08-31 21:01:32,947 - org.springframework.web.servlet.DispatcherServlet -19481 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet  - Null ModelAndView returned to DispatcherServlet with name 'springMVC': assuming HandlerAdapter completed request handling
[service] 2016-08-31 21:12:33,225 - org.springframework.web.servlet.DispatcherServlet -23378 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet  - Last-Modified value for [/mybatisRedis/s] is: -1
    [service] 2016-08-31 21:12:33,243 - org.mybatis.spring.SqlSessionUtils -23396 [http-nio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils  - Creating a new SqlSession
    [service] 2016-08-31 21:12:33,251 - org.mybatis.spring.SqlSessionUtils -23404 [http-nio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils  - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@377e5451] was not registered for synchronization because synchronization is not active
    [service] 2016-08-31 21:12:33,477 - com.erp.utils.redcache.RedisCache -23630 [http-nio-8080-exec-10] DEBUG com.erp.utils.redcache.RedisCache  - >>>>>>>>>>>>>>>>>>>>>>>>getObject:1716629384:864926724:com.erp.dao.TestMybatisMapper.selectByPrimaryKey:0:2147483647:select 
     
    TID, TNAME
   
    from TESTMYBATIS
    where TID = ?:6=[TestMybatis [tid=6, tname=asd]]
    [service] 2016-08-31 21:12:33,477 - com.erp.dao.TestMybatisMapper -23630 [http-nio-8080-exec-10] DEBUG com.erp.dao.TestMybatisMapper  - Cache Hit Ratio [com.erp.dao.TestMybatisMapper]: 1.0
    [service] 2016-08-31 21:12:33,477 - org.mybatis.spring.SqlSessionUtils -23630 [http-nio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils  - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@377e5451]
    TestMybatis [tid=6, tname=asd]
[service] 2016-08-31 21:12:33,482 - org.springframework.web.servlet.DispatcherServlet -23635 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet  - Null ModelAndView returned to DispatcherServlet with name 'springMVC': assuming HandlerAdapter completed request handling
    [service] 2016-08-31 21:12:33,482 - org.springframework.web.servlet.DispatcherServlet -23635 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet  - Successfully completed request

两次都是查询数据库里的数据,只不过第一次在查询之前我们先插入了一条数据,更新了缓存,

其实这并不能发挥redis的优势,更多的redis作为二级缓存服务器使用,实现我们自定义的二级缓存,如何利用号redis实现更加的灵活的实现数据的同步才是最重要的

package com.erp.controller;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.erp.dao.TestMybatisMapper;
import com.erp.model.TestMybatis;

@RestController
public class BaseController {

    @Autowired
    private TestMybatisMapper testMybatisMapper;

    @RequestMapping("s")
    public void test() {
        TestMybatis test = new TestMybatis();
        BigDecimal b = new BigDecimal("6");
        // test.setTid(b);
        // test.setTname("asd");
        // this.testMybatisMapper.insert(test);
        TestMybatis testMybatis = this.testMybatisMapper.selectByPrimaryKey(b);
        System.out.println(testMybatis.toString());
    }

}

这里我们需要注意一下我们好像不能使用junit和spring的那个test测试类,因为我们在那个好像每次都是从新加载的配置文件导致了每次都是重启的服务器一样

package com.erp.model;

import java.io.Serializable;
import java.math.BigDecimal;

public class TestMybatis implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private BigDecimal tid;

    private String tname;

    public BigDecimal getTid() {
        return tid;
    }

    public void setTid(BigDecimal tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname == null ? null : tname.trim();
    }

    @Override
    public String toString() {
        return "TestMybatis [tid=" + tid + ", tname=" + tname + "]";
    }

}
<cache type="com.erp.utils.redcache.LoggingRedisCache"/>
package com.erp.utils.redcache;

import org.apache.ibatis.cache.decorators.LoggingCache;

public class LoggingRedisCache extends LoggingCache {

    public LoggingRedisCache(String id) {
        super(new RedisCache(id));
    }

}
package com.erp.utils.redcache;

import org.junit.Test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class PoolResource {

    private static String ADDRESS = "localhost";
    private static int PORT = 6379;
    private static String PASSWORD = "wang";
    // 可用连接最大数目
    // -1 表示不限制
    private static int MAX_ACTIVE = 1024;
    // 控制一个pool最多有多少个空闲的jedis实例,默认是8
    private static int MAX_JEDIS = 200;

    // 等待的可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时,如果等待超时时间
    // 则抛出JedisConnectionException
    // redis.clients.jedis.exceptions.JedisConnectionException: Could not get a
    // resource from the pool
    private static int MAX_WAIT = 10000;
    private static int TIMROUT = 10000;

    // 在borrow一个jedis实例时,是否提前进行validate操作:true ,得到的jedis实例是可用的;
    private static boolean TEST_ON_BORROW = true;
    private static JedisPool jedisPool = null;

    /**
     * 初始化连接池
     */
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        //设置最大的连接数目,注意版本不同方法会有不同
        config.setMaxTotal(MAX_ACTIVE);
        config.setMaxIdle(MAX_JEDIS);
        config.setMaxWaitMillis(MAX_WAIT);
        config.setTestOnBorrow(TEST_ON_BORROW);
        jedisPool = new JedisPool(config, ADDRESS, PORT, TIMROUT, PASSWORD);
    }

    /**
     * 获取Jedis实例
     * 
     * @return
     */
    // synchronized是Java中的关键字,是一种同步锁。它修饰的对象有以下几种:
    // 1. 修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用的对象是调用这个代码块的对象;
    // 2. 修饰一个方法,被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象;
    // 3. 修改一个静态的方法,其作用的范围是整个静态方法,作用的对象是这个类的所有对象;
    // 4. 修改一个类,其作用的范围是synchronized后面括号括起来的部分,作用主的对象是这个类的所有对象。
    // 当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。

    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        // if (jedis != null) {
        // jedisPool.returnResource(jedis);
        // }
        if (jedis != null) {
            jedis.close();
        }
    }

    @Test
    public void testConnect() {
        for (int i = 0; i < 100; i++) {
            Jedis jedis = getJedis();
            System.out.println("Connect");
        }
    }
}
package com.erp.utils.redcache;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.cache.Cache;

import redis.clients.jedis.Jedis;

/**
 * 继承cache接口使用redis自定义实现mybatis的缓存技术
 * 
 * @author Administrator
 *
 */
public class RedisCache implements Cache {
    private static Log logger = LogFactory.getLog(RedisCache.class);
    private Jedis redisClient = createClient();
    /** The ReadWriteLock.读写锁 */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String id;

    public RedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>RedisCache:id=" + id);
        this.id = id;
    }

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

    public int getSize() {
        return Integer.valueOf(redisClient.dbSize().toString());
    }

    public void putObject(Object key, Object value) {
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
        redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
    }

    public Object getObject(Object key) {
        Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
        return value;
    }

    public Object removeObject(Object key) {
        return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
    }

    public void clear() {
        redisClient.flushDB();
    }

    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    protected static Jedis createClient() {
        try {
            //可以使用默认的config
            //JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
            return PoolResource.getJedis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("初始化连接池错误");
    }

}
<?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>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->
        <setting name="defaultExecutorType" value="REUSE" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
        <setting name="lazyLoadingEnabled" value="false" />
        <setting name="aggressiveLazyLoading" value="true" />
        <!-- <setting name="enhancementEnabled" value="true"/> -->
        <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
</configuration>
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
                        http://www.springframework.org/schema/cache 
                        http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com" />   
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/erp/mapping/*.xml"/>
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <!-- DAO接口所在包名(sql映射类所对应的方法接口所在的位置),Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.erp.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--通过注解管理事物@Transactional -->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>jdu</groupId>
    <artifactId>mybatisRedis</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisRedis Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- spring版本号 -->
        <spring.version>4.0.2.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.2.6</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
            <scope>test</scope>
        </dependency>
        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 使用Spring的aop时需要使用到aspectjweaver包,所以需要添加aspectjweaver包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
            <scope>test</scope>
        </dependency>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
        </dependency>
        <!-- 导入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <!-- D:\wanglihu\apacemaven\changku\oracle\ojdbc14\14\ojdbc14-14.jar -->
        <dependency>
            <groupId>oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>14</version>
        </dependency>
        <!--数据源 -->
        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- 上传组件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

        <!--添加json包 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier>
        </dependency>

    </dependencies>
    <build>
        <finalName>mybatisRedis</finalName>
    </build>
</project>

最后附上几个链接

http://www.tuicool.com/articles/quqmy2

http://blog.csdn.net/yjl33/article/details/50401211

扫描二维码关注公众号,回复: 4864653 查看本文章

这个也不错

http://www.cnblogs.com/wcyBlog/p/4402567.html

猜你喜欢

转载自blog.csdn.net/u012045045/article/details/86081101