【项目总结】秒杀系统の关于Redis_redis minevictableidletimemillis-程序员宅基地

技术标签: --------秒杀系统  ☆项目成长  spring整合Redis  Redis  

spring整合redis配置文件

redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.sentinel.port=26879
redis.pwd=
redis.database=0
redis.timeout=1000
redis.userPool=true
redis.pool.maxIdle=100
redis.pool.minIdle=10
redis.pool.maxTotal=200
redis.pool.maxWaitMillis=10000
redis.pool.minEvictableIdleTimeMillis=300000
redis.pool.numTestsPerEvictionRun=10
redis.pool.timeBetweenEvictionRunsMillis=30000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.testWhileIdle=true

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder order="1" location="classpath:redis.properties" ignore-unresolvable="true"/>
    <!-- Redis -->
    <!--组件扫描,需要添加pom依赖 spring-context -->
    <context:component-scan base-package="com.wj.redis" />

    <!-- 连接池参数 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.pool.maxIdle}" />
        <property name="minIdle" value="${redis.pool.minIdle}" />
        <property name="maxTotal" value="${redis.pool.maxTotal}" />
        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"></property>
        <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>
        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
        <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
        <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"></property>
    </bean>

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="jedisPoolConfig" />
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.pwd}" />
        <property name="usePool" value="${redis.userPool} " />
        <property name="database" value="${redis.database}" />
        <property name="timeout" value="${redis.timeout}" />
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />

        <!-- 序列化方式 建议key/hashKey采用StringRedisSerializer -->
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="hashValueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
        <!-- 开启REIDS事务支持 -->
        <property name="enableTransactionSupport" value="false" />
    </bean>

    <!-- 对string操作的封装 -->
    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <constructor-arg ref="jedisConnectionFactory" />
        <!-- 开启REIDS事务支持 -->
        <property name="enableTransactionSupport" value="false" />
    </bean>

</beans>

redis键

public interface KeyPrefix {
    public int expireSeconds();

    public String getPrefix();
}
public abstract class BasePrefix implements KeyPrefix {

    private int expireSeconds;

    private String prefix;

    public BasePrefix(String prefix) {
        this(0, prefix);
    }

    public BasePrefix(int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        this.prefix = prefix;
    }

    @Override
    public int expireSeconds() { //默认0代表永不过期
        return expireSeconds;
    }

    @Override
    public String getPrefix() {
        String className = getClass().getSimpleName();
        return className + ":" + prefix;
    }
}
public class GoodKey extends BasePrefix {
    public static GoodKey goodsList = new GoodKey(120, "gl");
    public static GoodKey goodsDetail = new GoodKey(60, "gd");
    public static GoodKey seckillGoodsStock = new GoodKey(0, "gs");
    private GoodKey(int expireSeconds, String prefix) {
        super(expireSeconds, prefix);
    }
}
public class SeckillKey extends BasePrefix {

    private SeckillKey(int expireSeconds, String prefix) {
        super(expireSeconds, prefix);
    }
    public static SeckillKey isGoodsOver = new SeckillKey(0, "go");
    public static SeckillKey getSeckillPath = new SeckillKey(60, "sp");
    public static SeckillKey getSeckillVerifyCode = new SeckillKey(300, "verifyCode");
}

这样做的好处:(Redis可视化工具)

RedisDao

public interface RedisDao {

    boolean isEmpty(Object obj);

    /**
     * 构建缓存key值
     *
     * @param key 缓存key
     * @return
     */
    String buildKey(String key);

    /**
     * 返回缓存的前缀
     *
     * @return CACHE_PREFIX_FLAG
     */
    String getCachePrefix();

    /**
     * 设置缓存的前缀
     *
     * @param cachePrefix
     */
    void setCachePrefix(String cachePrefix);

    /**
     * 关闭缓存
     *
     * @return true:成功 false:失败
     */
    boolean close();

    /**
     * 打开缓存
     *
     * @return true:存在 false:不存在
     */
    boolean openCache();

    /**
     * 检查缓存是否开启
     *
     * @return true:已关闭 false:已开启
     */
    boolean isClose();

    /**
     * 判断key值是否存在
     *
     * @param key 缓存的key
     * @return true:存在 false:不存在
     */
    boolean hasKey(String key);

    /**
     * 匹配符合正则的key
     *
     * @param patternKey
     * @return key的集合
     */
    Set<String> keys(String patternKey);

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    boolean del(String... key);

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    boolean delPattern(String key,long id);

    /**
     * 删除一组key值
     *
     * @param keys
     * @return true:成功 false:失败
     */
    boolean del(Set<String> keys);


    /**
     * 设置过期时间
     *
     * @param key     缓存key
     * @param seconds 过期秒数
     * @return true:成功 false:失败
     */
    boolean setExp(String key, long seconds);

    /**
     * 查询过期时间
     *
     * @param key 缓存key
     * @return 秒数
     */
    Long getExpire(String key);

    /**
     * 缓存存入key-value
     *
     * @param key   缓存键
     * @param value 缓存值
     * @return true:成功 false:失败
     */
    boolean setString(String key,long id, String value);

    /**
     * 缓存存入key-value
     *
     * @param key     缓存键
     * @param value   缓存值
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    boolean setString(String key, String value, long seconds);

    /**
     * 根据key取出String value
     *
     * @param key 缓存key值
     * @return String    缓存的String
     */
    String getString(String key,long id);

    /**
     * 去的缓存中的最大值并+1
     *
     * @param key 缓存key值
     * @return long    缓存中的最大值+1
     */
    long incr(String key);

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    boolean set(String key, Object obj);

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    boolean setObj(String key,long id, Object obj, long seconds);

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    boolean setGood(String key,long id, Object obj);
    /**
     * 取出缓存中存储的序列化对象
     *
     * @param key   缓存key
     * @param clazz 对象类
     * @return <T>	序列化对象
     */
    <T> T getObj(String key,long id, Class<T> clazz);

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key 缓存key
     * @param map 缓存map
     * @return true:成功 false:失败
     */
    <T> boolean setMap(String key, Map<String, T> map);

    /**
     * 取出缓存的map
     *
     * @param key 缓存key
     * @return map    缓存的map
     */
    @SuppressWarnings("rawtypes")
    Map getMap(String key);

    /**
     * 查询缓存的map的集合大小
     *
     * @param key 缓存key
     * @return int    缓存map的集合大小
     */
    long getMapSize(String key);


    /**
     * 根据key以及hashKey取出对应的Object对象
     *
     * @param key     缓存key
     * @param hashKey 对应map的key
     * @return object    map中的对象
     */
    Object getMapKey(String key, String hashKey);

    /**
     * 取出缓存中map的所有key值
     *
     * @param key 缓存key
     * @return Set<String> map的key值合集
     */
    Set<Object> getMapKeys(String key);

    /**
     * 删除map中指定的key值
     *
     * @param key     缓存key
     * @param hashKey map中指定的hashKey
     * @return true:成功 false:失败
     */
    boolean delMapKey(String key, String hashKey);

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key     缓存key
     * @param map     缓存map
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    <T> boolean setMapExp(String key, Map<String, T> map, long seconds);

    /**
     * map中加入新的key
     *
     * @param <T>
     * @param key     缓存key
     * @param hashKey map的Key值
     * @param value   map的value值
     * @return true:成功 false:失败
     */
    <T> boolean addMap(String key, String hashKey, T value);

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param key  缓存key
     * @param list 缓存List
     * @return true:成功 false:失败
     */
    <T> boolean setList(String key, List<T> list);

    /**
     * 根据key值取出对应的list合集
     *
     * @param key 缓存key
     * @return List<Object> 缓存中对应的list合集
     */
    <V> List<V> getList(String key);

    /**
     * 根据key值截取对应的list合集
     *
     * @param key   缓存key
     * @param start 开始位置
     * @param end   结束位置
     * @return
     */
    void trimList(String key, int start, int end);

    /**
     * 取出list合集中指定位置的对象
     *
     * @param key   缓存key
     * @param index 索引位置
     * @return Object    list指定索引位置的对象
     */
    Object getIndexList(String key, int index);

    /**
     * Object存入List
     *
     * @param prefix   缓存key
     * @param value List中的值
     * @return true:成功 false:失败
     */
    boolean addList(KeyPrefix prefix, Object value);

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param prefix     缓存key,秒数
     * @param list    缓存List
     * @return true:成功 false:失败
     */
    <T> boolean setList(KeyPrefix prefix,  List<T> list);

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key 缓存key
     * @param set 缓存set集合
     * @return true:成功 false:失败
     */
    <T> boolean setSet(String key, Set<T> set);

    /**
     * set集合中增加value
     *
     * @param key   缓存key
     * @param value 增加的value
     * @return true:成功 false:失败
     */
    boolean addSet(String key, Object value);

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key     缓存key
     * @param set     缓存set集合
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    <T> boolean setSet(String key, Set<T> set, long seconds);

    /**
     * 取出缓存中对应的set合集
     *
     * @param <T>
     * @param key 缓存key
     * @return Set<Object> 缓存中的set合集
     */
    <T> Set<T> getSet(String key);

    /**
     * 有序集合存入数值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @param score 评分
     * @return
     */
    boolean addZSet(String key, Object value, double score);

    /**
     * 从有序集合中删除指定值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @return
     */
    boolean removeZSet(String key, Object value);

    /**
     * 从有序集合中删除指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    boolean removeZSet(String key, long start, long end);

    /**
     * 从有序集合中获取指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    <T> Set<T> getZSet(String key, long start, long end);

}
/**
 * redis工具类
 */
@Service
public class RedisUtil implements RedisDao {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger LOG = LoggerFactory.getLogger(RedisUtil.class);
    private static String CACHE_PREFIX;
    private static boolean CACHE_CLOSED;

    @Override
    @SuppressWarnings("rawtypes")
    public boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            String str = obj.toString();
            if ("".equals(str.trim())) {
                return true;
            }
            return false;
        }
        if (obj instanceof List) {
            List<Object> list = (List<Object>) obj;
            if (list.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Map) {
            Map map = (Map) obj;
            if (map.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Set) {
            Set set = (Set) obj;
            if (set.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Object[]) {
            Object[] objs = (Object[]) obj;
            if (objs.length <= 0) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 构建缓存key值
     *
     * @param key 缓存key
     * @return
     */
    @Override
    public String buildKey(String key) {
        if (CACHE_PREFIX == null || "".equals(CACHE_PREFIX)) {
            return key;
        }
        return CACHE_PREFIX + ":" + key;
    }

    /**
     * 返回缓存的前缀
     *
     * @return CACHE_PREFIX_FLAG
     */
    @Override
    public String getCachePrefix() {
        return CACHE_PREFIX;
    }

    /**
     * 设置缓存的前缀
     *
     * @param cachePrefix
     */
    @Override
    public void setCachePrefix(String cachePrefix) {
        if (cachePrefix != null && !"".equals(cachePrefix.trim())) {
            CACHE_PREFIX = cachePrefix.trim();
        }
    }

    /**
     * 关闭缓存
     *
     * @return true:成功 false:失败
     */
    @Override
    public boolean close() {
        LOG.debug(" cache closed ! ");
        CACHE_CLOSED = true;
        return true;
    }

    /**
     * 打开缓存
     *
     * @return true:存在 false:不存在
     */
    @Override
    public boolean openCache() {
        CACHE_CLOSED = false;
        return true;
    }

    /**
     * 检查缓存是否开启
     *
     * @return true:已关闭 false:已开启
     */
    @Override
    public boolean isClose() {
        return CACHE_CLOSED;
    }

    /**
     * 判断key值是否存在
     *
     * @param key 缓存的key
     * @return true:存在 false:不存在
     */
    @Override
    public boolean hasKey(String key) {
        LOG.debug(" hasKey key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return false;
            }
            key = buildKey(key);
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 匹配符合正则的key
     *
     * @param patternKey
     * @return key的集合
     */
    @Override
    public Set<String> keys(String patternKey) {
        LOG.debug(" keys key :{}", patternKey);
        try {
            if (isClose() || isEmpty(patternKey)) {
                return Collections.emptySet();
            }
            return redisTemplate.keys(patternKey);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    @Override
    public boolean del(String... key) {
        LOG.debug(" delete key :{}", key.toString());
        try {
            if (isClose() || isEmpty(key)) {
                return false;
            }
            Set<String> keySet = new HashSet<>();
            for (String str : key) {
                keySet.add(buildKey(str));
            }
            redisTemplate.delete(keySet);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    @Override
    public boolean delPattern(String key,long id) {
        LOG.debug(" delete Pattern keys :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return false;
            }
            key = buildKey(key+id);
            redisTemplate.delete(redisTemplate.keys(key));
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 删除一组key值
     *
     * @param keys
     * @return true:成功 false:失败
     */
    @Override
    public boolean del(Set<String> keys) {
        LOG.debug(" delete keys :{}", keys.toString());
        try {
            if (isClose() || isEmpty(keys)) {
                return false;
            }
            Set<String> keySet = new HashSet<>();
            for (String str : keys) {
                keySet.add(buildKey(str));
            }
            redisTemplate.delete(keySet);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 设置过期时间
     *
     * @param key     缓存key
     * @param seconds 过期秒数
     * @return true:成功 false:失败
     */
    @Override
    public boolean setExp(String key, long seconds) {
        LOG.debug(" setExp key :{}, seconds: {}", key, seconds);
        try {
            if (isClose() || isEmpty(key) || seconds > 0) {
                return false;
            }
            key = buildKey(key);
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 查询过期时间
     *
     * @param key 缓存key
     * @return 秒数
     */
    @Override
    public Long getExpire(String key) {
        LOG.debug(" getExpire key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return 0L;
            }
            key = buildKey(key);
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0L;
    }

    /**
     * 缓存存入key-value
     *
     * @param key   缓存键
     * @param value 缓存值
     * @return true:成功 false:失败
     */
    @Override
    public boolean setString(String key,long id, String value) {
        LOG.debug(" setString key :{}, value: {}", key, value);
        try {
            if (isClose() || isEmpty(key) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key+id);
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入key-value
     *
     * @param key     缓存键
     * @param value   缓存值
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    @Override
    public boolean setString(String key, String value, long seconds) {
        LOG.debug(" setString key :{}, value: {}, timeout:{}", key, value, seconds);
        try {
            if (isClose() || isEmpty(key) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key);
            stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key取出String value
     *
     * @param key 缓存key值
     * @return String    缓存的String
     */
    @Override
    public String getString(String key,long id) {
        LOG.debug(" getString key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key+id);
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 去的缓存中的最大值并+1
     *
     * @param key 缓存key值
     * @return long    缓存中的最大值+1
     */
    @Override
    public long incr(String key) {
        LOG.debug(" incr key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return 0;
            }
            key = buildKey(key);
            return redisTemplate.opsForValue().increment(key, 1);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    @Override
    public boolean set(String key, Object obj) {
        LOG.debug(" set key :{}, value:{}", key, obj);
        try {
            if (isClose() || isEmpty(key) || isEmpty(obj)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForValue().set(key, obj);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    @Override
    public boolean setObj(String key,long id, Object obj, long seconds) {
        LOG.debug(" set key :{}, value:{}, seconds:{}", key, obj, seconds);
        try {
            if (isClose() || isEmpty(key) || isEmpty(obj)) {
                return false;
            }
            key = buildKey(key+id);
            redisTemplate.opsForValue().set(key, obj);
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    @Override
    public boolean setGood(String key, long id, Object obj) {
        LOG.debug(" set key :{}, value:{}, seconds:{}", key, obj);
        try {
            if (isClose() || isEmpty(key) || isEmpty(obj)) {
                return false;
            }
            key = buildKey(key+id);
            redisTemplate.opsForValue().set(key, obj);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中存储的序列化对象
     *
     * @param key   缓存key
     * @param clazz 对象类
     * @return <T>	序列化对象
     */
    @Override
    public <T> T getObj(String key,long id, Class<T> clazz) {
        LOG.debug(" get key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key+id);
            return (T) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key 缓存key
     * @param map 缓存map
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setMap(String key, Map<String, T> map) {
        try {
            if (isClose() || isEmpty(key) || isEmpty(map)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存的map
     *
     * @param key 缓存key
     * @return map    缓存的map
     */
    @SuppressWarnings("rawtypes")
    @Override
    public Map getMap(String key) {
        LOG.debug(" getMap key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key);
            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 查询缓存的map的集合大小
     *
     * @param key 缓存key
     * @return int    缓存map的集合大小
     */
    @Override
    public long getMapSize(String key) {
        LOG.debug(" getMap key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return 0;
            }
            key = buildKey(key);
            return redisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0;
    }


    /**
     * 根据key以及hashKey取出对应的Object对象
     *
     * @param key     缓存key
     * @param hashKey 对应map的key
     * @return object    map中的对象
     */
    @Override
    public Object getMapKey(String key, String hashKey) {
        LOG.debug(" getMapkey :{}, hashKey:{}", key, hashKey);
        try {
            if (isClose() || isEmpty(key) || isEmpty(hashKey)) {
                return null;
            }
            key = buildKey(key);
            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 取出缓存中map的所有key值
     *
     * @param key 缓存key
     * @return Set<String> map的key值合集
     */
    @Override
    public Set<Object> getMapKeys(String key) {
        LOG.debug(" getMapKeys key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key);
            return redisTemplate.opsForHash().keys(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除map中指定的key值
     *
     * @param key     缓存key
     * @param hashKey map中指定的hashKey
     * @return true:成功 false:失败
     */
    @Override
    public boolean delMapKey(String key, String hashKey) {
        LOG.debug(" delMapKey key :{}, hashKey:{}", key, hashKey);
        try {
            if (isClose() || isEmpty(key) || isEmpty(hashKey)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForHash().delete(key, hashKey);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key     缓存key
     * @param map     缓存map
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setMapExp(String key, Map<String, T> map, long seconds) {
        LOG.debug(" setMapExp key :{}, value: {}, seconds:{}", key, map, seconds);
        try {
            if (isClose() || isEmpty(key) || isEmpty(map)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForHash().putAll(key, map);
            redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * map中加入新的key
     *
     * @param <T>
     * @param key     缓存key
     * @param hashKey map的Key值
     * @param value   map的value值
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean addMap(String key, String hashKey, T value) {
        LOG.debug(" addMap key :{}, hashKey: {}, value:{}", key, hashKey, value);
        try {
            if (isClose() || isEmpty(key) || isEmpty(hashKey) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForHash().put(key, hashKey, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param key  缓存key
     * @param list 缓存List
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setList(String key, List<T> list) {
        LOG.debug(" setList key :{}, list: {}", key, list);
        try {
            if (isClose() || isEmpty(key) || isEmpty(list)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForList().leftPushAll(key, list.toArray());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key值取出对应的list合集
     *
     * @param key 缓存key
     * @return List<Object> 缓存中对应的list合集
     */
    @Override
    public <V> List<V> getList(String key) {
        LOG.debug(" getList key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key);
            return (List<V>) redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 根据key值截取对应的list合集
     *
     * @param key   缓存key
     * @param start 开始位置
     * @param end   结束位置
     * @return
     */
    @Override
    public void trimList(String key, int start, int end) {
        LOG.debug(" trimList key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return;
            }
            key = buildKey(key);
            redisTemplate.opsForList().trim(key, start, end);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 取出list合集中指定位置的对象
     *
     * @param key   缓存key
     * @param index 索引位置
     * @return Object    list指定索引位置的对象
     */
    @Override
    public Object getIndexList(String key, int index) {
        LOG.debug(" getIndexList key :{}, index:{}", key, index);
        try {
            if (isClose() || isEmpty(key) || index < 0) {
                return null;
            }
            key = buildKey(key);
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Object存入List
     *
     * @param prefix 缓存key
     * @param value  List中的值
     * @return true:成功 false:失败
     */
    @Override
    public boolean addList(KeyPrefix prefix, Object value) {
        LOG.debug(" addList key :{}, value:{}", prefix, value);
        try {
            if (isClose() || isEmpty(prefix.getPrefix()) || isEmpty(value)) {
                return false;
            }
            String key = buildKey(prefix.getPrefix());
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param prefix 缓存key,秒数
     * @param list   缓存List
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setList(KeyPrefix prefix, List<T> list) {
        LOG.debug(" setList key :{}, value:{}, seconds:{}", prefix.getPrefix(), list, prefix.expireSeconds());
        try {
            if (isClose() || isEmpty(prefix.getPrefix()) || isEmpty(list)) {
                return false;
            }
            String key = buildKey(prefix.getPrefix());
            redisTemplate.opsForList().leftPushAll(key, list.toArray());
            if (prefix.expireSeconds() > 0) {
                redisTemplate.expire(key, prefix.expireSeconds(), TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key 缓存key
     * @param set 缓存set集合
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setSet(String key, Set<T> set) {
        LOG.debug(" setSet key :{}, value:{}", key, set);
        try {
            if (isClose() || isEmpty(key) || isEmpty(set)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForSet().add(key, set.toArray());
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合中增加value
     *
     * @param key   缓存key
     * @param value 增加的value
     * @return true:成功 false:失败
     */
    @Override
    public boolean addSet(String key, Object value) {
        LOG.debug(" addSet key :{}, value:{}", key, value);
        try {
            if (isClose() || isEmpty(key) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForSet().add(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key     缓存key
     * @param set     缓存set集合
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    @Override
    public <T> boolean setSet(String key, Set<T> set, long seconds) {
        LOG.debug(" setSet key :{}, value:{}, seconds:{}", key, set, seconds);
        try {
            if (isClose() || isEmpty(key) || isEmpty(set)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForSet().add(key, set.toArray());
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中对应的set合集
     *
     * @param <T>
     * @param key 缓存key
     * @return Set<Object> 缓存中的set合集
     */
    @Override
    public <T> Set<T> getSet(String key) {
        LOG.debug(" getSet key :{}", key);
        try {
            if (isClose() || isEmpty(key)) {
                return null;
            }
            key = buildKey(key);
            return (Set<T>) redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 有序集合存入数值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @param score 评分
     * @return
     */
    @Override
    public boolean addZSet(String key, Object value, double score) {
        LOG.debug(" addZSet key :{},value:{}, score:{}", key, value, score);
        try {
            if (isClose() || isEmpty(key) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key);
            return redisTemplate.opsForZSet().add(key, value, score);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @return
     */
    @Override
    public boolean removeZSet(String key, Object value) {
        LOG.debug(" removeZSet key :{},value:{}", key, value);
        try {
            if (isClose() || isEmpty(key) || isEmpty(value)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForZSet().remove(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    @Override
    public boolean removeZSet(String key, long start, long end) {
        LOG.debug(" removeZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isClose() || isEmpty(key)) {
                return false;
            }
            key = buildKey(key);
            redisTemplate.opsForZSet().removeRange(key, start, end);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中获取指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    @Override
    public <T> Set<T> getZSet(String key, long start, long end) {
        LOG.debug(" getZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isClose() || isEmpty(key)) {
                return Collections.emptySet();
            }
            key = buildKey(key);
            return (Set<T>) redisTemplate.opsForZSet().range(key, start, end);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }


}

使用

  public List<PageData> getListAll() {
        List<PageData> list = redisDao.getList(GoodKey.goodsList.getPrefix());
        Map<Long,Boolean> localOverMap=MapUtil.getInstance();
        if (null == list || list.isEmpty()) {
            list = goodMapper.getListAll();
            redisDao.setList(GoodKey.goodsList, list);
            for (PageData pd : list) {
                long id= (Long) pd.get("id");
                redisDao.setGood(GoodKey.goodsDetail.getPrefix(),id,pd);
                localOverMap.put(id, false);
            }
        }
        return list;
    }

 

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

智能推荐

zram disksize 设置_use_dedup-程序员宅基地

文章浏览阅读3.4k次。zram disksize 设置小内存项目:1G,2G,3G RAMzram disksize设置.高通:高通的设置比较简单:相关代码:init.qcom.post_boot.shif [ -f /sys/block/zram0/disksize ]; thenif [ -f /sys/block/zram0/use_dedup ]; thenecho 1 > /sys/block/zram0/use_dedupfiif [ $MemTotal -le5242_use_dedup

学画画软件app推荐_在游戏中学习!化学app软件推荐!-程序员宅基地

文章浏览阅读281次。今天中学化学园给大家推荐几款超有趣的教育软件APP,大家可以自行搜索下载,又萌又有趣,在玩乐中还能学到知识!手机要有足够内存哦~~~!下面几款适用于苹果系统~~~1.神奇的化学元素简介:可以高效帮助您记忆有关元素的基本知识。适用对象:初高中学生2.烧杯简介:150多种药剂、300多种神奇的化学反应任你尝试。安全、有趣生动、随时随地做各种化学实验,生动直观,充满乐趣~适用对象:高中学生锂..._化学游戏软件

QMI8658A-EVB 评估板--产品简介_qmi8658a中文资料-程序员宅基地

文章浏览阅读618次。QMA8658A 是一款功能强大的6轴加速度传感器,其内置了3轴加速度计和3轴陀螺仪,能够同时测量三个方向的加速度和角速度。该传感器广泛应用于无人机、机器人、智能手机等领域。为了帮助开发人员快速评估和开发基于QMA8658A的解决方案,我们推出了QMA8658A-EVB全面的评估板。该评估板精心设计,预置了所有必需的硬件接口,兼容I2C和SPI接口,方便与任意MCU处理器进行连接和通信。此外,我们还提供了详细的驱动程序和使用指南,以便开发者能够轻松使用该评估板进行二次开发。4.1 I2C接口。_qmi8658a中文资料

iMeta | 宁波大学附属第一医院崔翰斌团队综述缺血性心脏病相关肠道微生物及菌群代谢物研究进展...-程序员宅基地

文章浏览阅读551次。点击蓝字 关注我们缺血性心脏病相关肠道微生物及菌群代谢物研究进展iMeta主页:http://www.imeta.science综 述●原文链接DOI: https://doi.org/10.1002/imt2.94● 2023年2月26日,宁波大学附属第一医院崔翰斌团队、浙江省动脉粥样硬化疾病精准医学研究重点实验室范勇团队在iMeta在线发表了题为“Microbiota-related ..._与急性心肌梗死有关的微生物

图形图形处理方面的一位微软专家的主页,_automated video looping with progressive dynamism-程序员宅基地

文章浏览阅读2.6k次,点赞2次,收藏5次。刚在Github上分享了一些不错的代码http://hhoppe.com/ Hugues Hoppe »DemosPublicationsTalksAcademicProfessionalMisc Hugues Hoppe [pronunciation]Principal researche_automated video looping with progressive dynamism

AOP实现权限拦截_apo拦截控制层-程序员宅基地

文章浏览阅读497次。AOP实现权限拦截注解名称:CheckUnSysAdmin注解实现类:CommonAspectController层方法上引入注解名称:CheckUnSysAdminpackage com.sf.XWFS.aop;import java.lang.annotation.*;/** * @author cc * Desc 校验除超管外的角色,都进行拦截 */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType_apo拦截控制层

随便推点

【代码优化】for-each代替普通的for循环或者while循环_c++中的while循环可有什么替代-程序员宅基地

文章浏览阅读2.8k次。对于集合的遍历首选方法是for-eachfor(Element e :c){ doSomething(e);}这是1.5版本之后的做法;java1.5之前使用的是Iterator迭代器。为了弄清楚为啥比普通的for循环或者whlie循环好,请看一下代码Iterator i=c.iterator();while(i.hasNext()){_c++中的while循环可有什么替代

微信公众号网页静默授权/非静默授权(uniapp版)_微信公众号静默授权-程序员宅基地

文章浏览阅读7.7k次,点赞5次,收藏33次。一、问题为什么要进行网页授权?首先我们进行网页授权的需求是,获取用户信息、最主要是获取openid唯一值,可以用于用户登录、支付等功能,这时候就需要进行网页授权获取用户的信息以及openid。二、静默授权/非静默授权在操作之前可以先提前看看网页授权官方文档静默授权snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid;用来获取进入页面的用户的openid的,并且自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)。非静默授权snsapi_user_微信公众号静默授权

A Key Volume Mining Deep Framework for Action Recognition-程序员宅基地

文章浏览阅读235次。A Key Volume Mining Deep Framework for Action Recognition_a key volume mining deep framework for action recognition

python创建窗体_python生成窗口-程序员宅基地

文章浏览阅读3.9k次。广告关闭腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元!2、python生成目录树上述 cmd 方式虽然可以生成目录树,但是并不美观,让我们用 python 实现。 2.1 标准库pathlib介绍python有一个标准文件路径处理库 os.path ,从 python3.4 开始,python 又加入了一个标准库 pathlib ,该库..._python创建一个窗口

PowerDesigner16 时序图_使用powerdesiger 画出时序图有接口 控制-程序员宅基地

文章浏览阅读5.1k次,点赞5次,收藏10次。时序图(Sequence Diagram)是显示对象之间交互的图,这些对象是按时间顺序排列的。顺序图中显示的是参与交互的对象及其对象之间消息交互的顺序。时序图中包括的建模元素主要有:角色(Actor)、对象(Object)、生命线(Lifeline)、控制焦点(Focus of control)/ 激活(Activation)、消息(Message)、组合片段(Combined Fragments_使用powerdesiger 画出时序图有接口 控制

Doris系列17-动态分区_dynamic_partition.history_partition_num-程序员宅基地

文章浏览阅读1.2k次。文章目录一. 动态分区概述1.1 原理1.2 使用方式1.3 动态分区规则参数1.4 创建历史分区规则1.5 注意事项二. 案例2.1 案例12.2 案例22.3 案例3参考:一. 动态分区概述动态分区是在 Doris 0.12 版本中引入的新功能。旨在对表级别的分区实现生命周期管理(TTL),减少用户的使用负担。目前实现了动态添加分区及动态删除分区的功能。动态分区只支持 Range 分区。名词解释:FE:Frontend,Doris 的前端节点。负责元数据管理和请求接入。BE:Backend_dynamic_partition.history_partition_num

推荐文章

热门文章

相关标签