spring boot使用redis

首先加配置到application.properties中:

spring.redis.host=dev-redis.host
spring.redis.password=111111
spring.redis.port=6379
spring.redis.timeout=30000
spring.redis.pool.max-active=200
spring.redis.pool.min-idle=10
spring.redis.pool.max-idle=50
spring.redis.pool.max-wait=300
spring.redis.database=0

其次创建BaseRedis基类:



public class BaseRedis<K,V> {

    @Autowired
    protected RedisTemplate<K, V> redisTemplate;

    /**
     * 设置redisTemplate
     * @param redisTemplate the redisTemplate to set
     */
    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取 RedisSerializer
     * <br>------------------------------<br>
     */
    protected RedisSerializer<String> getRedisSerializer() {
        return redisTemplate.getStringSerializer();
    }
}

最后添加CacheService继承BaseRedis:



@Service
public class CacheService extends BaseRedis<String, String> {

    /**
     * set element to zset by score
     * @param key
     * @param score
     * @param value
     * @param <T>
     * @return
     */
    public <T> Boolean setPush(String key, Long score, T value) {
        String objSerial = Utils.toJson(value);
        Boolean isSuccess = redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            Boolean bool = redisConnection.zAdd(key.getBytes(), score, objSerial.getBytes());
            return bool;
        });
        return isSuccess;
    }

    /**
     * get list of element on the range between start time and stop time
     * @param key
     * @param start
     * @param stop
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> setPopRangeByScore(String key, Long start, Long stop, Class<T> clazz) {
        List<T> clazzList = new ArrayList<T>();
        redisTemplate.execute((RedisCallback<T>) redisConnection -> {
            Set<byte[]> bytes = redisConnection.zRangeByScore(key.getBytes(), start, stop);
            bytes.forEach(aByte -> clazzList.add(Utils.parseJson(aByte, clazz)));
            return null;
        });
        return clazzList;

    }

    /**
     * remove element of zset score between start time and stop time
     * @param key
     * @param start
     * @param stop
     */
    public void removeByScore(String key, Long start, Long stop) {
        redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            Long along = redisConnection.zRemRangeByScore(key.getBytes(), start, stop);
            return along > 0;
        });
    }
}

猜你喜欢

转载自blog.csdn.net/nethackatschool/article/details/53539443