RedisUtils工具类,设置缓存,然后需要在删除,更新插入的时候清空缓存,保持redis和mysql的数据一致

Posted 指导毕业设计Monkey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RedisUtils工具类,设置缓存,然后需要在删除,更新插入的时候清空缓存,保持redis和mysql的数据一致相关的知识,希望对你有一定的参考价值。

文章目录

1.查询的时候先查询缓存,如果为空就会以查询数据库,然后设置值到缓存

public List<ClmHospitalLccc> queryClmHospitalLccc() 
        List<ClmHospitalLccc> list;
        List<ClmHospitalLccc> lv01 = new ArrayList<>();
        List<ClmHospitalLccc> lv02 = new ArrayList<>();
        List<ClmHospitalLccc> lv03 = new ArrayList<>();
        int count = 0;

        RedisUtils redisUtils = RedisUtils.getInstance();
        if(redisUtils.get(CustomerConstants.QUERY_XILL_HOSPITAL_TREE) !=null)
            log.info("医院索引缓存数据:",(List<ClmHospitalLccc>) redisUtils.get(CustomerConstants.QUERY_XILL_HOSPITAL_TREE));
            return (List<ClmHospitalLccc>) redisUtils.get(CustomerConstants.REGION_CUSTOMER,CustomerConstants.QUERY_XILL_HOSPITAL_TREE);
        
        //查询所有医院代码数据
        list = this.hospitalCodeUpholdMapper.initPageList();


        //按节点遍历
        for(ClmHospitalLccc clmHospitalLccc:list)
            if(clmHospitalLccc.getHscode() != null && !"".equals(clmHospitalLccc.getHscode()))
                if(clmHospitalLccc.getHscode().trim().length() == 2)
                    lv01.add(clmHospitalLccc);
                
                if(clmHospitalLccc.getHscode().trim().length() == 4)
                    lv02.add(clmHospitalLccc);
                
                if(clmHospitalLccc.getHscode().trim().length() == 6)
                    lv03.add(clmHospitalLccc);
                
            


        
        for(ClmHospitalLccc clmHospitalLccc02:lv02)
            List children = new ArrayList();
            for(ClmHospitalLccc clmHospitalLccc03:lv03)
                if(clmHospitalLccc03.getHscode().substring(0,4).equals(clmHospitalLccc02.getHscode()))
                    Map<String, Object> map = new HashMap();
                    map.put("hscode", clmHospitalLccc03.getHscode());
                    map.put("hsname", clmHospitalLccc03.getHsname());
                    map.put("children", clmHospitalLccc03.getChildren());
                    children.add(map);
                
            
            if (children.size() > 0) 
                clmHospitalLccc02.setChildren(children);
            
        


        for(ClmHospitalLccc clmHospitalLccc01:lv01)
            List children = new ArrayList();
            for(ClmHospitalLccc clmHospitalLccc02:lv02)
                if(clmHospitalLccc02.getHscode().substring(0,2).equals(clmHospitalLccc01.getHscode()))
                    Map<String, Object> map = new HashMap();
                    map.put("hscode", clmHospitalLccc02.getHscode());
                    map.put("hsname", clmHospitalLccc02.getHsname());
                    map.put("children", clmHospitalLccc02.getChildren());
                    children.add(map);
                
            
            if (children.size() > 0) 
                clmHospitalLccc01.setChildren(children);
            
        
        log.info("医院索引查询-数据缓存处理前:",System.currentTimeMillis());
        redisUtils.set(CustomerConstants.REGION_CUSTOMER, CustomerConstants.QUERY_XILL_HOSPITAL_TREE, lv01,30*24*3600);
        log.info("医院索引查询-数据缓存处理后:",System.currentTimeMillis());
        return lv01;
    



2.在进行修改(insert,delete,update)操作的时候进行 删除缓存(这样就会下次查询的时候缓存为空,又会重新设置缓存)

3.缓存工具类

package com.sunline.framework.redis.utils;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.util.StringUtils;

import com.sunline.framework.redis.constants.CttRedis.Region;

import lombok.extern.slf4j.Slf4j;

 
/**
 * 
 * ClassName: RedisUtils <br/>
 * Function: TODO redis cache 工具类. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2019年10月17日 下午2:40:29 <br/>
 *
 */
@Slf4j
public class RedisUtils    

	public static final String regionDefault = Region.REDIS_OBJ;

	private static RedisUtils redisUtils;

	private RedisTemplate<Serializable, Object> redisTemplate;


	public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) 
		this.redisTemplate = redisTemplate;
	

	public static RedisUtils getInstance() 
		if (null == redisUtils) 
			synchronized (RedisUtils.class) 
				if (null == redisUtils) 
					log.info("缓存实例为空,初始化开始...");
					redisUtils = new RedisUtils();
					log.info("缓存实例为空,初始化完成...");
				
			
		
		return redisUtils;
	
 

	/**
	 * 设置缓存(永不过期)
	 * @param region 缓存块名称(注意命名规范)
	 * @param key 缓存key
	 * @param value 缓存值 
	 */
	public Object get(String region, String key) 
		try 
			String factKey = this.getKeyName(region, key);
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			return operations.get(factKey);
		 catch (Exception e) 
			log.error("根据region[],key[]获取缓存时异常!", region, key);
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
		return null;
	
 
	public Object get(String key) 
		return this.get(this.regionDefault, key);
	
 

	/**
	 * 设置缓存(永不过期)
	 * @param region 缓存块名称(注意命名规范)
	 * @param key 缓存key
	 * @param value 缓存值 
	 */
	public void set(String region, String key, Object value) 
		try 
			if (!StringUtils.isEmpty(key)) 
				String factKey = this.getKeyName(region, key);
				ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
				operations.set(factKey, value);
			
		 catch (Exception e) 
			log.error("根据region[],key[]存储缓存时异常!", region, key);
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	

	/**
	 * 设置缓存
	 * @param region 缓存块名称(注意命名规范)
	 * @param key 缓存key
	 * @param value 缓存值
	 * @param expireTime 到期时间(单位:秒)
	 */
	public void set(String region, String key, Object value, int expireTime) 
		try 
			if (!StringUtils.isEmpty(key)) 
				String factKey = this.getKeyName(region, key);
				ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
				operations.set(factKey, value);
				redisTemplate.expire(factKey, expireTime, TimeUnit.SECONDS);
			
		 catch (Exception e) 
			log.error("根据region[],key[]存储缓存时异常!", region, key);
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	

	/**
	 * 设置缓存 (使用默认块)
	 * @param key 缓存key
	 * @param value 缓存值 
	 */
	public void set(String key, Object value) 
		this.set(regionDefault, key, value);
	

	/**
	 * 设置缓存
	 * @param region 缓存块名称(注意命名规范)
	 * @param key 缓存key
	 * @param value 缓存值
	 * @param expireTime 到期时间(单位:秒)
	 */
	public void set(String key, Object value, int expireTime) 
		try 
			String factKey = this.getKeyName(regionDefault, key);
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(factKey, value);
			redisTemplate.expire(factKey, expireTime, TimeUnit.SECONDS);
		 catch (Exception e) 
			log.error("根据key[],expireTime[]存储缓存时异常!", key, expireTime);
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	
 
	/**
	 * 获取全部keys信息
	 * @param pattern
	 * @return
	 */
	public Set<Serializable> keys(String pattern) 
		try 
			return redisTemplate.keys(pattern);
		 catch (Exception e) 
			e.printStackTrace();
			return null;
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	

	/**
	 * 删除缓存
	 * @param region 缓存块
	 * @param key 键
	 */
	public void remove(String region, String key) 
		try 
			String factKey = this.getKeyName(region, key);
			if (exists(factKey)) 
				redisTemplate.delete(factKey);
			
		 catch (Exception e) 
			log.error("根据region[],key[]清理缓存时异常!", region, key);
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	 
	
	/**
	 * 根据默认块+key删除缓存
	 * @param key
	 */
	public void remove(String key) 
		try 
			String factKey = this.getKeyName(this.regionDefault, key);
			if (exists(factKey)) 
				redisTemplate.delete(factKey);
			
		 catch (Exception e) 
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	
 
	private boolean exists(String key) 
		try 
			return redisTemplate.hasKey(key);
		 catch (Exception e) 
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
		return false;
	
	
	/**
	 * 根据前缀key模糊匹配清理缓存对象信息
	 * @param prefix
	 */
	public void clearAllStartingWith(String prefix) 
		try 
			Set<Serializable> setData = this.keys(prefix);
			if (null != setData) 
				redisTemplate.delete(setData);
			
		 catch (Exception e) 
			e.printStackTrace();
		 finally 
			RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
		
	
 

	/**
	 * 生成缓存的 key
	 * @param region
	 * @param key
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected String getKeyName(String region, Object key) 
		if (StringUtils.isEmpty(region)) 
			region = regionDefault;
		
		if (key instanceof Number) 
			return region + ":I:" + key;
		 else 
			Class keyClass = key.getClass();
			if (String.class.SpringBoot实战:整合Redismybatis,封装RedisUtils工具类等(附源码)

RedisUtils工具类

RedisUtils工具类

单机版 RedisUtils({基本操作封装工具类})

SpringBoot项目中创建redisUtils,在调用redisUtils的静态方法时,报空指针异常

用泛型写Redis缓存与数据库操作工具类