Redis二次封装

本文介绍了一个用于操作Redis的Java客户端API及其实现细节。该API提供了丰富的功能,包括设置和获取键值、操作列表和集合等。通过使用JSON序列化库Gson进行数据转换,使得复杂对象的存储变得简单高效。
摘要由CSDN通过智能技术生成

------------------------------------------------------接口START----------------------------------------------------------------

package com.api;
import java.util.List;
import java.util.Map;
import java.util.Set;

public interface IRedisService {
    void delete(String... var1);

    boolean set(String var1, String var2);

    boolean set(String var1, String var2, long var3);

    boolean set(String var1, Object var2);

    boolean set(String var1, Object var2, long var3);

    boolean hSet(String var1, String var2, Object var3);

    String get(String var1);

    Set<String> getKeys(String var1);

    <T> T get(String var1, Class<T> var2);

    <T> T hGet(String var1, String var2, Class<T> var3);

    <T> boolean setList(String var1, List<T> var2);

    <T> List<T> getList(String var1, Class<T> var2);

    <T> Map<String, T> getMap(String var1, Class<T> var2);

    Map<String, String> getMap(String var1);

    void hDelete(String var1, String var2);

    boolean exist(String var1);

    long llen(String var1);

    long lpush(String var1, Object var2);

    long lpush(String var1, Object var2, long var3);

    String lpop(String var1);

    <T> T lpop(String var1, Class<T> var2);

    long rpush(String var1, Object var2);

    long rpush(String var1, Object var2, long var3);

    String rpop(String var1);

    <T> T rpop(String var1, Class<T> var2);

    List<String> lrange(String var1, long var2, long var4);

    <T> List<T> lrange(String var1, long var2, long var4, Class<T> var6);

    void ldel(String var1, int var2);

    long getExpireTime(String var1);
}

------------------------------------------------------接口END----------------------------------------------------------------

------------------------------------------------------接口实现START----------------------------------------------------------------

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.common.util.GSONFloatAdapter;
import com.api.IRedisService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class RedisServiceImpl implements IRedisService {
    private Gson gson;
    @Resource
    private RedisTemplate<String, ?> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public RedisServiceImpl() {
        this.gson = (new GsonBuilder()).disableHtmlEscaping().registerTypeAdapter(Float.TYPE, new GSONFloatAdapter()).registerTypeAdapter(Float.class, new GSONFloatAdapter()).create();
    }

    public void delete(String... keys) {
        if (keys != null && keys.length > 0) {
            this.redisTemplate.execute((connection) -> {
                RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
                List<byte[]> lst = new ArrayList();
                String[] var5 = keys;
                int var6 = keys.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    String key = var5[var7];
                    lst.add(serializer.serialize(key));
                }

                byte[][] bkeys = new byte[lst.size()][];
                lst.toArray(bkeys);
                connection.del(bkeys);
                return null;
            });
        }

    }

    public boolean set(String key, String value) {
        boolean result = (Boolean)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
            return true;
        });
        return result;
    }

    public boolean set(String key, String value, long expireTime) {
        boolean result = (Boolean)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
            connection.expire(serializer.serialize(key), expireTime);
            return true;
        });
        return result;
    }

    public boolean set(String key, Object value) {
        if (value != null) {
            String str = this.gson.toJson(value);
            return this.set(key, str);
        } else {
            return false;
        }
    }

    public boolean set(String key, Object value, long expireTime) {
        if (value != null) {
            String str = this.gson.toJson(value);
            return this.set(key, str, expireTime);
        } else {
            return false;
        }
    }

    public boolean hSet(String key, String field, Object value) {
        boolean result = (Boolean)this.redisTemplate.execute((connection) -> {
            if (value == null) {
                return false;
            } else {
                String str;
                if (value.getClass() == String.class) {
                    str = (String)value;
                } else {
                    str = this.gson.toJson(value);
                }

                RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
                connection.hSet(serializer.serialize(key), serializer.serialize(field), serializer.serialize(str));
                return true;
            }
        });
        return result;
    }

    public String get(String key) {
        String result = (String)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            byte[] value = connection.get(serializer.serialize(key));
            return (String)serializer.deserialize(value);
        });
        return result;
    }

    public Set<String> getKeys(String keyLike) {
        return this.stringRedisTemplate.keys(keyLike);
    }

    public <T> T get(String key, Class<T> clz) {
        String json = this.get(key);
        return StringUtils.isNotBlank(json) ? this.gson.fromJson(json, clz) : null;
    }

    public <T> T hGet(String key, String field, Class<T> clz) {
        String result = (String)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            byte[] value = connection.hGet(serializer.serialize(key), serializer.serialize(field));
            return (String)serializer.deserialize(value);
        });
        if (StringUtils.isNotBlank(result)) {
            return clz == String.class ? result : this.gson.fromJson(result, clz);
        } else {
            return null;
        }
    }

    public <T> boolean setList(String key, List<T> list) {
        return this.set(key, (Object)list);
    }

    public <T> List<T> getList(String key, Class<T> clz) {
        String json = this.get(key);
        if (!StringUtils.isNotBlank(json)) {
            return null;
        } else {
            List datalist = (List)this.gson.fromJson(json, List.class);
            List<T> list = new ArrayList();
            Iterator var6 = datalist.iterator();

            while(var6.hasNext()) {
                Object data = var6.next();
                String str = this.gson.toJson(data);
                T t = this.gson.fromJson(str, clz);
                list.add(t);
            }

            return list;
        }
    }

    public <T> Map<String, T> getMap(String key, Class<T> clz) {
        Map<String, T> resultMap = this.hGetAll(key, clz);
        return resultMap == null ? null : resultMap;
    }

    public Map<String, String> getMap(String key) {
        Map<String, String> resultMap = this.hGetAll(key, (Class)null);
        return resultMap == null ? null : resultMap;
    }

    private <T> Map hGetAll(String key, Class<T> clz) {
        Map<byte[], byte[]> map = (Map)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            Map<byte[], byte[]> mapByte = connection.hGetAll(serializer.serialize(key));
            return mapByte;
        });
        if (null == map) {
            return null;
        } else {
            Map resultMap = new HashMap(map.size());
            Iterator<Entry<byte[], byte[]>> iterator = map.entrySet().iterator();
            String mapKey = "";
            String mapValue = "";
            Entry entry;
            if (null != clz) {
                while(iterator.hasNext()) {
                    entry = (Entry)iterator.next();
                    mapKey = new String((byte[])entry.getKey());
                    mapValue = new String((byte[])entry.getValue());
                    resultMap.put(mapKey, this.gson.fromJson(mapValue, clz));
                }
            } else {
                while(iterator.hasNext()) {
                    entry = (Entry)iterator.next();
                    mapKey = new String((byte[])entry.getKey());
                    mapValue = new String((byte[])entry.getValue());
                    resultMap.put(mapKey, mapValue);
                }
            }

            return resultMap;
        }
    }

    public void hDelete(String key, String field) {
        this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            connection.hDel(serializer.serialize(key), new byte[][]{serializer.serialize(field)});
            return null;
        });
    }

    public boolean exist(String key) {
        Assert.notNull(key, "key can not be null!");
        boolean result = (Boolean)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            return connection.exists(serializer.serialize(key));
        });
        return result;
    }

    public long llen(String key) {
        Assert.notNull(key, "key can not be null!");
        long result = (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            return connection.lLen(serializer.serialize(key));
        });
        return result;
    }

    public long lpush(String key, Object value) {
        Assert.notNull(key, "key can not be null!");
        Assert.notNull(value, "value can not be null!");
        String str = this.gson.toJson(value);
        return (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            return connection.lPush(serializer.serialize(key), new byte[][]{serializer.serialize(str)});
        });
    }

    public long lpush(String key, Object value, long expireTime) {
        Assert.notNull(key, "key can not be null!");
        Assert.notNull(value, "value can not be null!");
        String str = this.gson.toJson(value);
        return (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            long push = connection.lPush(serializer.serialize(key), new byte[][]{serializer.serialize(str)});
            connection.expire(serializer.serialize(key), expireTime);
            return push;
        });
    }

    public String lpop(String key) {
        Assert.notNull(key, "key can not be null!");
        return (String)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            byte[] value = connection.lPop(serializer.serialize(key));
            return (String)serializer.deserialize(value);
        });
    }

    public <T> T lpop(String key, Class<T> clz) {
        String json = this.lpop(key);
        return StringUtils.isNotBlank(json) ? this.gson.fromJson(json, clz) : null;
    }

    public long rpush(String key, Object value) {
        Assert.notNull(key, "key can not be null!");
        Assert.notNull(value, "value can not be null!");
        String str = this.gson.toJson(value);
        return (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            return connection.rPush(serializer.serialize(key), new byte[][]{serializer.serialize(str)});
        });
    }

    public long rpush(String key, Object value, long expireTime) {
        Assert.notNull(key, "key can not be null!");
        Assert.notNull(value, "value can not be null!");
        String str = this.gson.toJson(value);
        return (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            long push = connection.rPush(serializer.serialize(key), new byte[][]{serializer.serialize(str)});
            connection.expire(serializer.serialize(key), expireTime);
            return push;
        });
    }

    public String rpop(String key) {
        Assert.notNull(key, "key can not be null!");
        return (String)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            byte[] value = connection.rPop(serializer.serialize(key));
            return (String)serializer.deserialize(value);
        });
    }

    public <T> T rpop(String key, Class<T> clz) {
        String json = this.rpop(key);
        return StringUtils.isNotBlank(json) ? this.gson.fromJson(json, clz) : null;
    }

    public List<String> lrange(String key, long start, long end) {
        Assert.notNull(key, "key can not be null!");
        return (List)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            List<byte[]> bytes = connection.lRange(serializer.serialize(key), start, end);
            List<String> resultList = new ArrayList(bytes.size());
            bytes.forEach((b) -> {
                resultList.add(new String(b));
            });
            return resultList;
        });
    }

    public <T> List<T> lrange(String key, long start, long end, Class<T> clz) {
        Assert.notNull(key, "key can not be null!");
        Assert.notNull(clz, "clz can not be null!");
        return (List)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            List<byte[]> bytes = connection.lRange(serializer.serialize(key), start, end);
            List<T> resultList = new ArrayList(bytes.size());
            bytes.forEach((b) -> {
                resultList.add(this.gson.fromJson(new String(b), clz));
            });
            return resultList;
        });
    }

    public void ldel(String key, int pace) {
        Assert.notNull(key, "key can not be null!");
        Assert.isTrue(pace > 0, "pace must greater than zero!");
        this.redisTemplate.executePipelined((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            long size = this.llen(key);
            if (size <= 0L) {
                return null;
            } else {
                byte[] deleteFlag = serializer.serialize("delete");

                for(int i = 1; (long)i < size; i += pace + 1) {
                    connection.lSet(serializer.serialize(key), (long)i, deleteFlag);
                }

                connection.lRem(serializer.serialize(key), size, deleteFlag);
                return null;
            }
        });
    }

    public long getExpireTime(String key) {
        return (Long)this.redisTemplate.execute((connection) -> {
            RedisSerializer<String> serializer = this.redisTemplate.getStringSerializer();
            return connection.pTtl(serializer.serialize(key), TimeUnit.SECONDS);
        });
    }
}

------------------------------------------------------接口实现END---------------------------------------------------------------

------------------------------------------------------接口实现GSON适配器START---------------------------------------------------------------

package com.common.util;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;

public class GSONFloatAdapter implements JsonSerializer<Float>, JsonDeserializer<Float> {
    public GSONFloatAdapter() {
    }

    public Float deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!"".equals(json.getAsString()) && !"null".equals(json.getAsString())) {
            try {
                return json.getAsFloat();
            } catch (NumberFormatException var5) {
                throw new JsonSyntaxException(var5);
            }
        } else {
            return 0.0F;
        }
    }

    public JsonElement serialize(Float src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src);
    }
}

------------------------------------------------------接口实现GSON适配器END---------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柠檬不萌c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值