Mybatis-custom cache-redis second-level cache, mybatis -- redis

Source: Internet
Author: User

Mybatis-custom cache-redis second-level cache, mybatis -- redis

The general principle of the second-level cache has been introduced in the mybatis level-1 cache level-2 cache. Next we will use redis to implement the second-level cache. The environment is springmvc + mybatis + redis

Step 1. Introduce maven dependencies related to redis
<! -- Spring-redis implementation --> <dependency> <groupId> org. springframework. data </groupId> <artifactId> spring-data-redis </artifactId> <version> 1.6.2.RELEASE </version> </dependency> <! -- Redis client jar --> <dependency> <groupId> redis. clients </groupId> <artifactId> jedis </artifactId> <version> 2.8.0 </version> </dependency>
Step 2: Create a New redis configuration redis. xml, redis. properties
<? 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" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.0.xsd "default-autowire =" byName "default-lazy-init =" false "> <! -- Redis data source --> <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 connection pool management factory --> <bean id = "jedisConnectionFactory" class = "org. springframework. data. redis. connection. jedis. jedisConnectionFactory "p: hostName =" $ {redis. host} "p: port =" $ {redis. port} "p: password =" $ {redis. pass} "p: poolConfig-ref =" poolConfig "/> <! -- Use the intermediate class to solve RedisCache. static injection of jedisConnectionFactory to enable MyBatis to implement third-party cache --> <bean id = "redisCacheTransfer" class = "com. yihaomen. mybatis. cache. redisCacheTransfer "> <property name =" jedisConnectionFactory "ref =" jedisConnectionFactory "/> </bean> </beans>

 

redis.host=192.168.31.55redis.port=6379redis.pass=redis.maxIdle=300redis.maxActive=600redis.maxWait=1000redis.testOnBorrow=true

 

Step 3. Introduce redis. xml to the spring configuration file applicationContext. xml
<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><import resource="redis.xml"/>

 

Step 4. Create a cache implementation class RedisCache
Package com. yihaomen. mybatis. cache; import org. apache. ibatis. cache. cache; 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. ti Ons. jedisConnectionException; import java. util. concurrent. locks. readWriteLock; import java. util. concurrent. locks. reentrantReadWriteLock;/***** @ ProjectName: springmvc-mybatis * @ Description: Use a third-party memory database Redis as a secondary cache * @ author: lisen * @ date: optional /11/8 */public class RedisCache implements Cache {private static JedisConnectionFactory jedisConnectionFactory; private final String id; private final ReadWri TeLock readWriteLock = new ReentrantReadWriteLock (); public RedisCache (final String id) {if (id = null) {throw new IllegalArgumentException ("Cache instances requan ID");} this. id = id;} public static void setJedisConnectionFactory (JedisConnectionFactory jedisConnectionFactory) {RedisCache. jedisConnectionFactory = jedisConnectionFactory;} @ Override public String getId () {return this. id;} 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 () ;}} 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;} 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 ;}@ 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 () ;}} 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 ;} public ReadWriteLock getReadWriteLock () {return this. readWriteLock ;}}

 

Step 5. Create an intermediate class RedisCacheTransfer and complete Static injection of RedisCache. jedisConnectionFactory
Package com. yihaomen. mybatis. cache; import org. springframework. beans. factory. annotation. autowired; import org. springframework. data. redis. connection. jedis. jedisConnectionFactory;/***** @ ProjectName: springmvc-mybatis * @ Description: creates an intermediate class RedisCacheTransfer and completes RedisCache. static injection of jedisConnectionFactory, * Static injection intermediate class * @ author: lisen * @ date: Medium /11/8 */public class principal {@ Autowired public void principal (JedisConnectionFactory jedisConnectionFactory) {RedisCache. setJedisConnectionFactory (jedisConnectionFactory );}}

 

Step 6. Add the MyBatis second-level cache to mapper (User. xml)
<?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.yihaomen.mybatis.dao.UserMapper">    <cache type="com.yihaomen.mybatis.cache.RedisCache"/>
  <select id="selectUserByID" parameterType="int" resultType="User" >
  select * from `user` where id = #{id}
  </select>
</mapper>

We can also configure the cache configuration at the SQL level to determine whether or not they need to use or refresh the cache. We often perform this based on two attributes: userCache and flushCache, userCache indicates whether cache is required, and flushCache indicates whether cache needs to be refreshed after insertion, for example

<Select... flushCache = "false" useCache = "true"/>

<Insert... flushCache = "true"/>

<Update... flushCache = "true"/>

<Delete... flushCache = "true"/>

Step 7. Enable Level 2 caching in mybatis-config.xml files
<Settings> <! -- This configuration enables or disables caching for the global Er (level-2 cache) --> <setting name = "cacheEnabled" value = "true"/> </setting>

 

Step 8. Unit Test
package com.yihaomen.service.test;import com.yihaomen.mybatis.dao.UserMapper;import com.yihaomen.mybatis.model.User;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;/** *    *  @ProjectName: springmvc-mybatis  *  @Description: *  @author: lisen *  @date: 2017/11/9   */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath:applicationContext.xml"})public class UserSpringTest {    @Autowired    private UserMapper userMapper;    @Test    public void selectUserById() {        List<User> users = userMapper.selectUserById(11L);    }}

 

 

Https://gitee.com/huayicompany/springmvc-mybatis

Refer:

Blog, http://blog.csdn.net/xiadi934/article/details/50786293

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.