青柠小记 2021-12-30 13:58:30

redis轻量工具类

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 500
        min-idle: 0


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public <E> void put(String key, E value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    public <E> E getSingle(String key, Class<E> cls) {
        Object res = redisTemplate.opsForValue().get(key);
        return cast(res, cls);
    }

    public <E> List<E> getList(String key, Class<E> cls) {
        Object res = redisTemplate.opsForValue().get(key);
        return castList(res, cls);
    }


    @SuppressWarnings("unchecked")
    private static <T> T cast(Object obj, Class<T> cls) {
        return (T) obj;
    }


    @SuppressWarnings("unchecked")
    private static <T> List<T> castList(Object obj, Class<T> cls) {
        return (List<T>) obj;
    }
}

评论

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.138.0. UTC+08:00, 2024-12-22 11:26
浙ICP备14020137号-1 $访客地图$