springboot mybatis配置二级缓存redis

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35201754/article/details/80880564

1.pom依赖


<!--redis  -->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-redis -->
     <dependency>
         <groupId>org.mybatis.caches</groupId>
         <artifactId>mybatis-redis</artifactId>
         <version>1.0.0-beta2</version>
     </dependency>

2.定义一个序列化的工具类

package com.yutu.platform.commUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	  public static byte[] serialize(Object object) {
	        ObjectOutputStream oos = null;
	        ByteArrayOutputStream baos = null;
	        try {
	            // 序列化
	            baos = new ByteArrayOutputStream();
	            oos = new ObjectOutputStream(baos);
	            oos.writeObject(object);
	            byte[] bytes = baos.toByteArray();
	            return bytes;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return null;
	    }
	 
	    public static Object unserialize(byte[] bytes) {
	        ByteArrayInputStream bais = null;
	        try {
	            // 反序列化
	            bais = new ByteArrayInputStream(bytes);
	            ObjectInputStream ois = new ObjectInputStream(bais);
	            return ois.readObject();
	        } catch (Exception e) {
	 
	        }
	        return null;
	    }
}

3.创建缓存实现类MybatisRedisCache实现 Cache

package com.yutu.platform.service.common.impl;

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 com.yutu.platform.commUtils.SerializeUtil;

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

public class MybatisRedisCache implements Cache{
	private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
	 
    private Jedis redisClient = createReids();
 
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 
    private String id;
 
    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
        this.id = id;
    }
 
    @Override
    public String getId() {
        return this.id;
    }
 
    @Override
    public int getSize() {
 
        return Integer.valueOf(redisClient.dbSize().toString());
    }
 
    @Override
    public void putObject(Object key, Object value) {
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
        redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
    }
 
    @Override
    public Object getObject(Object key) {
        Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
        return value;
    }
 
    @Override
    public Object removeObject(Object key) {
        return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
    }
 
    @Override
    public void clear() {
        redisClient.flushDB();
    }
 
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
 
    protected static Jedis createReids() {
        JedisPool pool = new JedisPool("127.0.0.1", 6379);
        return pool.getResource();
    }
}

5.配置mapper层的xml


其中type对应的是自己创建的cache接口的实现类

<mapper namespace="com.yutu.platform.mapper.workManage.TRulesRegulationsMapper" >
  <cache type="com.yutu.platform.service.common.impl.MybatisRedisCache" blocking="false"
           flushInterval="0" readOnly="true" size="1024" eviction="FIFO"/>
  <resultMap id="BaseResultMap" type="com.yutu.platform.entity.workManage.TRulesRegulations" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="code" property="code" jdbcType="VARCHAR" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="type" property="type" jdbcType="VARCHAR" />
    <result column="publicName" property="publicname" jdbcType="VARCHAR" />
    <result column="publicTime" property="publictime" jdbcType="VARCHAR" />
    <result column="publicRange" property="publicrange" jdbcType="VARCHAR" />
    <result column="uploadDate" property="uploaddate" jdbcType="VARCHAR" />
    <result column="unitName" property="unitname" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="VARCHAR" />
    <result column="content" property="content" jdbcType="VARCHAR" />
  </resultMap>

在需要使用缓存的方法上

<select id="findTRulesRegulationsForCode" resultMap="BaseResultMap" useCache="true">
  	select pb.id, pb.code, pb.title, pb.type, pb.publicName, pb.publicTime, pb.publicRange, pb.uploadDate,bp.simpleName unitName, 
    if(pb.status="02","已发布","未发布") as status
    , content
  	from t_rules_regulations pb
  	left join t_base_party_units bp on pb.unitName = bp.unitCode
  	<where>
  		<if test="code!=null">
  		    pb.code = #{code}
  		</if>
  	</where>
  
  </select>

添加的redis配置为

 <cache type="com.yutu.platform.service.common.impl.MybatisRedisCache" blocking="false"
           flushInterval="0" readOnly="true" size="1024" eviction="FIFO"/>

useCache="true"

6.实体类继承Serializable

package com.yutu.platform.entity.workManage;

import java.io.Serializable;


public class TRulesRegulations  implements Serializable{
	   private static final long serialVersionUID = 4673186153813605228L;
    /**
     * 
     */
    private Integer id;

    /**
     * 
     */
    private String code;

    /**
     * 标题
     */
    private String title;

    /**
     * 类型 01群团工作 02统一战线
     */
    private String type;

    /**
     * 发布人
     */
    private String publicname;

    /**
     * 发布时间
     */
    private String publictime;

    /**
     * 发布范围
     */
    private String publicrange;

    /**
     * 上传时间
     */
    private String uploaddate;

    /**
     * 发布单位
     */
    private String unitname;

    /**
     * 发布状态01未发布 02已发布
     */
    private String status;

    /**
     * 文档内容
     */
    private String content;

    /**
     * 
     * @return id 
     */
    public Integer getId() {
        return id;
    }

    /**
     * 
     * @param id 
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 
     * @return code 
     */
    public String getCode() {
        return code;
    }

    /**
     * 
     * @param code 
     */
    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    /**
     * 标题
     * @return title 标题
     */
    public String getTitle() {
        return title;
    }

    /**
     * 标题
     * @param title 标题
     */
    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    /**
     * 类型 01群团工作 02统一战线
     * @return type 类型 01群团工作 02统一战线
     */
    public String getType() {
        return type;
    }

    /**
     * 类型 01群团工作 02统一战线
     * @param type 类型 01群团工作 02统一战线
     */
    public void setType(String type) {
        this.type = type == null ? null : type.trim();
    }

    /**
     * 发布人
     * @return publicName 发布人
     */
    public String getPublicname() {
        return publicname;
    }

    /**
     * 发布人
     * @param publicname 发布人
     */
    public void setPublicname(String publicname) {
        this.publicname = publicname == null ? null : publicname.trim();
    }

    /**
     * 发布时间
     * @return publicTime 发布时间
     */
    public String getPublictime() {
        return publictime;
    }

    /**
     * 发布时间
     * @param publictime 发布时间
     */
    public void setPublictime(String publictime) {
        this.publictime = publictime == null ? null : publictime.trim();
    }

    /**
     * 发布范围
     * @return publicRange 发布范围
     */
    public String getPublicrange() {
        return publicrange;
    }

    /**
     * 发布范围
     * @param publicrange 发布范围
     */
    public void setPublicrange(String publicrange) {
        this.publicrange = publicrange == null ? null : publicrange.trim();
    }

    /**
     * 上传时间
     * @return uploadDate 上传时间
     */
    public String getUploaddate() {
        return uploaddate;
    }

    /**
     * 上传时间
     * @param uploaddate 上传时间
     */
    public void setUploaddate(String uploaddate) {
        this.uploaddate = uploaddate == null ? null : uploaddate.trim();
    }

    /**
     * 发布单位
     * @return unitName 发布单位
     */
    public String getUnitname() {
        return unitname;
    }

    /**
     * 发布单位
     * @param unitname 发布单位
     */
    public void setUnitname(String unitname) {
        this.unitname = unitname == null ? null : unitname.trim();
    }

    /**
     * 发布状态01未发布 02已发布
     * @return status 发布状态01未发布 02已发布
     */
    public String getStatus() {
        return status;
    }

    /**
     * 发布状态01未发布 02已发布
     * @param status 发布状态01未发布 02已发布
     */
    public void setStatus(String status) {
        this.status = status == null ? null : status.trim();
    }

    /**
     * 文档内容
     * @return content 文档内容
     */
    public String getContent() {
        return content;
    }

    /**
     * 文档内容
     * @param content 文档内容
     */
    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }
}

7.查看是否实现缓存


参考:https://www.cnblogs.com/jeffen/p/6286324.html

展开阅读全文

没有更多推荐了,返回首页