Solo  当前访客:0 开始使用

Spring中访问Redis


1、依赖导入

    <dependency>

            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.0.7.RELEASE</version>
        </dependency>

2、接口定义

public interface RedisRepo<HK, T extends Serializable> {

    /**
     * Get the value object by the id from redis
     *
     * @param id
     * @return
     */
    T findById(HK id);

    /**
     * Returns one value(key-value) randomly by the specified key's wildcard pattern(DO NOT contains the key's prefix string)
     *
     * @param wildcardPattern eg: Given key "REDIS_KEY_PREFIX_AGENT_COOKIES_ACC:GONGSHANG_GUANGZHOU:USERACC1" - value"v1",
     *                        and "REDIS_KEY_PREFIX_AGENT_COOKIES_ACC:GONGSHANG_GUANGZHOU:USERACC2" - value "v2", then findOne("GONGSHANG_GUANGZHOU*") will return one value
     *
     * @return
     */
    T findOne(HK wildcardPattern);

    /**
     * Returns all the values by the specified key's wildcard pattern(DO NOT contains the key's prefix string)
     *
     * @param wildcardPattern
     * @return
     */
    List<T> findAll(HK wildcardPattern);


    /**
     * Store the value object to the redis
     *
     * @param id
     * @param vObj
     */
    void save(HK id, T vObj);


    /**
     * Store the value object to the redis with expire time specified
     *
     * @param id
     * @param vObj
     * @param timeout time unit: second(秒)
     */
    void save(HK id, T vObj, long timeout);

    /**
     * Delete the value object in the redis hash
     *
     * @param id
     */
    void delete(HK id);

    /**
     *  TODO: // Only support Redis String type
     */
    <T1> List<T1> getListForJsonString(HK key, Class<T1> clz);

}

3、实现类

public abstract class AbstractRedisRepo<HK extends String, T extends Serializable> implements RedisRepo<HK, T> {


    @Autowired(required = false)
    private RedisTemplate<HK, T> redisTemplate;
    private final String redisKeyPrefix;
//    abstract protected HK formatRedisKey(HK id);


    public AbstractRedisRepo(String redisKeyPrefix) {
        this.redisKeyPrefix = redisKeyPrefix;
    }

    @Override
    public T findById(HK id) {
        ValueOperations<HK, T> valueOperations = this.redisTemplate.opsForValue();
        return valueOperations.get(formatRedisKey(id));
    }

    @Override
    public T findOne(HK wildcardPattern) {
        Set<HK> keys = redisTemplate.keys(formatRedisKey(wildcardPattern));

        Iterator<HK> iterator = keys.iterator();

        if (keys != null && iterator.hasNext())
            return redisTemplate.opsForValue().get(iterator.next());

        return null;
    }

    @Override
    public List<T> findAll(HK wildcardPattern) {

        List<T> rslList = new ArrayList<>();

        Set<HK> keys = redisTemplate.keys(formatRedisKey(wildcardPattern));

        Iterator<HK> iterator = keys.iterator();
        while(iterator.hasNext()){
            rslList.add(redisTemplate.opsForValue().get(iterator.next()));
        }

        return rslList;
    }

    /**
     * 该方法返回的其实去掉前缀的部分KEY,并原生redis的keys功能
     *
     * @param id
     * @return
     */
    @Deprecated
    public Set<String> keys(HK id){
        Set<HK> keys=redisTemplate.keys(formatRedisKey(id));
        Iterator<HK> keyIterator=keys.iterator();

        Set<String> newKeys=new HashSet<>();
        while (keyIterator.hasNext()){
            String key=keyIterator.next();
            key=key.replace(redisKeyPrefix+":","");
            newKeys.add(key);
        }

        return newKeys;
    }

    @Override
    public <T1> List<T1> getListForJsonString(HK id, Class<T1> clz) {
        T json = findById(id);
        if(json!=null && json instanceof String){
            return JSONUtil.toList((String)json, clz);
        }
        return null;
    }

    @Override
    public void save(HK id, T vObj){
        this.redisTemplate.opsForValue().set(formatRedisKey(id), vObj);
    }

    @Override
    public void save(HK id, T vObj, long timeout) {
        this.redisTemplate.opsForValue().set(formatRedisKey(id), vObj, timeout, TimeUnit.SECONDS);
    }

    @Override
    public void delete(HK id) {
        this.redisTemplate.delete(formatRedisKey(id));
    }

    protected HK formatRedisKey(HK id) {
        StringBuilder key = new StringBuilder();
        key.append(redisKeyPrefix);
        key.append(":");
        key.append(id);
        return (HK)key.toString();
    }
}

4、使用

public class UnifyUserRedisRepository extends AbstractRedisRepo<String, UnifyUser> {
    private final static String REDIS_KEY_PREFIX = "REDIS_KEY_PREFIX_AGENT_UNIFY_USER";

    public UnifyUserRedisRepository() {
        super(REDIS_KEY_PREFIX);
    }
}


标题:Spring中访问Redis
作者:Nick1407
地址:https://nick1407.com/articles/2019/07/08/1562576517118.html

0 0