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.equals(keyClass) || StringBuffer.class.equals(keyClass)
					|| StringBuilder.class.equals(keyClass)) {
				return region + ":S:" + key;
			}
		}
		return region + ":O:" + key;
	}
	

	public long generate( ) {
		RedisAtomicLong redisAtomicLong = new RedisAtomicLong(new Date().toString(), redisTemplate.getConnectionFactory());
		return redisAtomicLong.incrementAndGet();
	}
	public long generate(String key) {
		
		RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
		return redisAtomicLong.incrementAndGet();
	}

	public long generate(String key,Date expireTime) {
		RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
		redisAtomicLong.expireAt(expireTime);
		return redisAtomicLong.incrementAndGet();
	}

	public long generate(String key,int increment) {
		RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
		return redisAtomicLong.addAndGet(increment);
	}
	public long generate(String key,int increment,Date expireTime) {
		RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
		redisAtomicLong.expireAt(expireTime);
		return redisAtomicLong.addAndGet(increment);
	}

    /**
     * 
    * getRedisTemplate:(获取缓存模板). <br/>
    * TODO(这里描述这个方法的注意事项 – 可选).<br/>
    *
    * @since 2020-08-17
     */
    public RedisTemplate<Serializable, Object> getRedisTemplate() {
        return redisTemplate;
    }
	/**
	 * 向集合中添加元素,返回是否添加成功,1成功  0 失败
	 * @param region
	 * @param key
	 * @param value
	 * @return
	 */
	public  Long setValueToSet(String region, String key, String value) {
		String factKey = this.getKeyName(region, key);
		return redisTemplate.opsForSet().add(factKey,value);
	}

	/**
	 * 将元素从集合中移除,移除成功,返回1 ,否则0
	 */
	public Long removeFromSet(String region, String key, String value){
		String factKey = this.getKeyName(region, key);
		return redisTemplate.opsForSet().remove(factKey,value);
	}
	public Set<Object> getSet(String region, String key){
		String factKey = this.getKeyName(region,key);
		return redisTemplate.opsForSet().members(factKey);
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
对于mysql/redis等6大数据库,在7种java业务中的选型与调优可以从以下角度来考虑: 1. 事务型业务:对于需要保证ACID(原子性、一致性、隔离性和持久性)特性的业务,如支付系统或订单系统,适合选择MySQL这类关系型数据库。可以通过使用InnoDB引擎来提供事务支持,并进行合理的索引设计与数据表分区来提高性能。 2. 缓存型业务:对于频繁读取的数据,如热门商品、热门文章等,可以选择使用Redis等内存数据库作为缓存,提高读取速度。可以使用Redis提供的Hash类型或Sorted Set等数据结构来存储和操作数据。 3. 日志型业务:对于需要记录用户操作日志或系统日志的业务,可以选择使用MySQL数据库。可以使用数据库的分区表或者分库分表技术来分散写入压力,使用数据库索引来提高查询效率。 4. 大数据量存储:对于需要处理大量数据的业务,如用户行为数据分析或日志分析等,可以选择使用Hadoop等大数据处理平台,将数据存储在分布式文件系统中,如HDFS,再通过Hive或HBase等工具进行查询和分析。 5. 高并发读写:对于需要处理高并发读写请求的业务,如社交网络或在线视频等,可以考虑使用分布式数据库,如TiDB或Cassandra等,以支持水平扩展和负载均衡,提高系统的并发能力。 6. 实时计算:对于需要实时计算的业务,如推荐系统或风控系统,可以选择使用流式处理框架,如Flink或Spark Streaming等,结合类似Kafka等高吞吐量消息队列,对数据进行实时处理和计算。 在选型和调优时,需要根据具体业务需求和系统性能要求来选择合适的数据库,并进行合理的设计和配置。同时,还需要进行性能测试和监控,根据实际情况进行优化,如合理调整数据库参数、优化SQL查询语句、缓存数据等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有时间指导毕业设计

觉得写的好的话可以给我打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值