基于RedisTemplate封装Redis

一. 概述

1.1 什么是RedisTemplate?

  • RedisTemplate是对Redis的封装,它能够简化与Redis进行数据交互的细节,提升功能效率和降低使用难度。

1.2 使用方式:

  • 引入Spring-Redis的启动器,在yml等配置文件中配置了相关的Redis地址等信息即可使用。@Autowired引入RedisTemplate即可使用。

1.3 为什么还要封装Redis呢?

  • 在使用Redis的过程中,它的RedisTemplate会将数据转为二进制,我们在使用桌面版Redis客户端的时候(RedisDesktopManager)只能看到二进制看不到人容易识别的名称。
  • 封装后可以进行统一设置,统一管理,更方便使用。
  • 使用多级目录易于使用。

二. 图示:

2.1 使用RedisTemplate的set方法存储的数据:

在这里插入图片描述

可以看出来,RedisTemplate不易于读取;我们封装后有文件夹包裹,更易于使用;


三. 示例代码(SpringBoot+SpringCloud环境)

3.1 yml配置文件图示:

在这里插入图片描述

spring:
  redis:
    database: 10         # Redis数据库索引(默认为0)
    host: localhost     # Redis服务器地址
    port: 6379          # Redis服务器连接端口
    password:     # Redis服务器连接密码(默认为空)
    expire:
      headerExpire:  #重点.....key不能带有特殊字符,必须符合变量的定意规范(字母,下划线,数字)
        [SYS_VERIFYIMAGE]: 600 # 10分钟
    pool:
      max-active: 600    # 连接池最大连接数(使用负值表示没有限制)
      max-idle: 300      # 连接池中的最大空闲连接
      max-wait: 2000    # 连接池最大阻塞等待时间(使用负值表示没有限制)
      min-idle: 5       # 连接池中的最小空闲连接
      timeout: 0        # 连接超时时间(毫秒)   

3.2 目录结构以及文件名:

  • 图示:
    在这里插入图片描述

  • 文件名: RedisConfig RedisExpireConfig RedisService RedisConstans

3.3 RedisConfig.java

package com.cdmtc.redis.config;

import com.cdmtc.redis.RedisService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;


/**
 * @create_by: zhanglei
 * @craete_time 2019/7/16
 */
@Configuration
public class RedisConfig{

	
	/**
	 * 初始化redis header对应的过期时间
	 * @return
	 */
	@Bean
	public RedisExpireConfig redisExpireConfig() {
		return new RedisExpireConfig();
	}
	
	@Bean
	public RedisService redisService(StringRedisTemplate stringRedisTemplate) {
		return new RedisService(stringRedisTemplate);
	}
}

3.4 RedisExpireConfig

package com.cdmtc.redis.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @create_by: zhanglei
 * @craete_time 2019/7/16
 */
@ConfigurationProperties(prefix = "spring.redis.expire")
public class RedisExpireConfig {
	/**
	 * redis中header对应的过期时间
	 */
	private Map<String, Long> headerExpire;

	public Map<String, Long> getHeaderExpire() {
		return headerExpire;
	}

	public void setHeaderExpire(Map<String, Long> headerExpire) {
		this.headerExpire = headerExpire;
	}

	/**
	 * 获取对应header设置的过期时间
	 * 
	 * @param header
	 * @return
	 */
	public long getExpire4Header(String header) {
		if(!CollectionUtils.isEmpty(headerExpire)) {
			Long result = headerExpire.get("["+header+"]");
			if(null == result ) {
				result = 0L;
			}
			return result;
		}
		return 0L;
	}
}

3.5 RedisService.java

package com.cdmtc.redis;

import com.cdmtc.redis.config.RedisExpireConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @create_by: zhanglei
 * @craete_time 2019/7/16
 */
@SuppressWarnings("unchecked")
public class RedisService {

	private Logger logger = LoggerFactory.getLogger(RedisService.class);

	@SuppressWarnings("rawtypes")
	private RedisTemplate template;
	@SuppressWarnings({ "rawtypes" })
	private ListOperations listOpe;
	@SuppressWarnings("rawtypes")
	private ValueOperations valueOpe;
	@SuppressWarnings("rawtypes")
	private HashOperations hashOpe;
	@SuppressWarnings("rawtypes")
	private ZSetOperations zsetOpe;
	@SuppressWarnings("rawtypes")
	private SetOperations setOpe;
	@Autowired
	private RedisExpireConfig expireConfig;

	@SuppressWarnings("rawtypes")
	public RedisService(RedisTemplate template) {
		this.template = template;
		listOpe = template.opsForList();
		valueOpe = template.opsForValue();
		hashOpe = template.opsForHash();
		zsetOpe = template.opsForZSet();
		setOpe = template.opsForSet();
		this.template = template;
	}

	private String getKey(String head, String key) {
		return head + ":" + key;
	}

	public String get(String head, String key) {
		return (String) valueOpe.get(getKey(head, key));
	}

	public void set(String head, String key, String value) {

		valueOpe.set(getKey(head, key), value);
		// 设置过期时间
		expire(head, key);
	}

	/**
	 * 以配置文件为准,为reids设置对应的过期时间
	 * 
	 * @param head
	 * @param key
	 * @return
	 */
	private boolean expire(String head, String key) {
		long times = expireConfig.getExpire4Header(head);
		if (times > 0) {
			try {
				return expire(head, key, times, TimeUnit.SECONDS);
			} catch (Exception e) {
				logger.warn("过期时间设置失败{head:" + head + ",key:" + key + "}。");
			}
		}
		return false;
	}

	/**
	 * 以传入的时间为准,设置相应的过期时间
	 * 
	 * @param head
	 * @param key
	 * @param timeout
	 * @param unit
	 * @return
	 */
	public boolean expire(String head, String key, long timeout, TimeUnit unit) {
		return template.expire(getKey(head, key), timeout, unit);
	}

	public boolean zadd(String head, String key, String member, double score) {
		boolean result = zsetOpe.add(getKey(head, key), member, score);
		expire(head,key);
		return result;
	}

	/**
	 * 按分数从小到大获取指定数量
	 * 
	 * @param head
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<String> rang(String head, String key, long start, long end) {
		return zsetOpe.range(getKey(head, key), start, end);
	}

	/**
	 * 按分数从大到小获取指定数量
	 * 
	 * @param head
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<String> reverseRange(String head, String key, long start, long end) {
		return zsetOpe.reverseRange(getKey(head, key), start, end);
	}

	/**
	 * 获取指定key下成员的分数
	 * 
	 * @param head
	 * @param key
	 * @param member
	 * @return
	 */
	public double score(String head, String key, String member) {
		return zsetOpe.score(getKey(head, key), member);
	}

	/**
	 * 获取排名--score低-->高
	 * 
	 * @param head
	 * @param key
	 * @param member
	 * @return
	 */
	public long rank(String head, String key, String member) {
		return zsetOpe.rank(getKey(head, key), member);
	}

	/**
	 * 获取排名--score高-->低
	 * 
	 * @param head
	 * @param key
	 * @param member
	 * @return
	 */
	public long reverseRank(String head, String key, String member) {
		return zsetOpe.reverseRank(getKey(head, key), member);
	}

	/**
	 * 获取指定起始位置的排行榜信息
	 * 
	 * @param head
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<String>> reverseRangeWithScores(String head, String key, long start,
			long end) {
		return zsetOpe.reverseRangeWithScores(getKey(head, key), start, end);
	}

	/**
	 * 获取批量hashkey对应value对象json字符串
	 * 
	 * @param head
	 * @param key
	 * @param fields
	 * @param
	 * @param        <
	 * @return
	 */
	public List<String> hmget(String head, String key, Collection<?> fields) {
		if (CollectionUtils.isEmpty(fields)) {
			return null;
		}

		return hashOpe.multiGet(getKey(head, key), fields);
	}

	/**
	 * hset 操作
	 * 
	 * @param head
	 * @param key
	 * @param field
	 * @param value
	 */
	public void hset(String head, String key, String field, String value) {
		hashOpe.put(getKey(head, key), field, value);
		expire(head, key);
	}

	/**
	 * 获取所有的field
	 * 
	 * @param head
	 * @param key
	 * @return
	 */
	public Set<String> keys(String head, String key) {
		return hashOpe.keys(getKey(head, key));
	}

	/**
	 * 通过field获取value
	 * 
	 * @param head
	 * @param key
	 * @param field
	 * @return
	 */
	public String hget(String head, String key, String field) {
		return (String)hashOpe.get(getKey(head, key), field);
	}

	/**
	 * 获取set里对应成员
	 * 
	 * @param head
	 * @param key
	 * @param
	 * @return
	 */
	public Set<String> smembers(String head, String key) {
		return setOpe.members(getKey(head, key));
	}

	/**
	 * 通过field获取value
	 * 
	 * @param head
	 * @param key
	 * @param value
	 * @return
	 */
	public long sadd(String head, String key, String value) {
		long result = setOpe.add(getKey(head, key), value);
		expire(head, key);
		return result;
	}

	/**
	 * 在value后面追加值
	 * 
	 * @param head
	 * @param key
	 * @param addString
	 */
	public int append(String head, String key, String addString) {
		return valueOpe.append(getKey(head, key), addString);
	}
	
	/**
	 * 加锁机制 true加锁成功 false加锁失败
	 * 
	 * @param head
	 * @param key
	 * @param lockValue
	 */
	public boolean setnx(String head, String key, String lockValue) {
		boolean success = valueOpe.setIfAbsent(getKey(head, key), lockValue);
		if (success) {
			// 设置过期时间
			expire(head, key);
		}
		return success;
	}

	/**
	 * 删除KEY
	 * 
	 * @param head
	 * @param key
	 */
	public boolean delete(String head, String key) {
		return template.delete(getKey(head, key));
	}
	
	public long rightPush(String head, String key,String value) {
		return listOpe.rightPush(getKey(head, key), value);
	}

	/**
	 *
	 * @param head
	 * @param key
	 * @param member
	 * @return
	 */
	public Double incrementScore(String head, String key,String member,Double score) {
		return zsetOpe.incrementScore(getKey(head, key),member,score);

	}

	/**
	 * @description:
	 * @param head
	 * @param key
	 * @param map
	 * @return: void
	 */
	public void hmset(String head ,String key,Map<? extends String, ? extends String> map){
		if (!CollectionUtils.isEmpty(map)){
			hashOpe.putAll(getKey(head,key),map);
			expire(head, key);
		}
	}
	/**
	 *
	 * @param head
	 * @param key
	 * @param filed
	 * @param value
	 * @return
	 */
	public Double Hincrby(String head,String key,String filed,Double value){
		return hashOpe.increment(getKey(head, key), filed, value);
	}

	/**
	 * 删除hash数据结构
	 *
	 * @param head
	 * @param key
	 */
	public Long hdel(String head, String key,String field) {
		return hashOpe.delete(getKey(head,key),field);
	}

	/**
	 * 判断可以是否存在
	 * @param head
	 * @param key
	 * @return
	 */
	public boolean hasKey(String head, String key) {
		return template.hasKey(getKey(head,key));
	}

}

3.6 RedisConstans

package com.cdmtc.redis.constans;
/**
 * @create_by: zhanglei
 * @craete_time 2019/7/16
 */
public class RedisConstans {
    public static String SYS_VERIFYIMAGE="SYS_VERIFYIMAGE";     // webSocket 发送消息类型
}