RedisTemplate常用方法封装

2022-07-22,,,

redistemplate常用方法封装

序列化和配置

package com.gitee.ccsert.mall.common.redis.config;

import com.fasterxml.jackson.annotation.jsonautodetect;
import com.fasterxml.jackson.annotation.propertyaccessor;
import com.fasterxml.jackson.databind.objectmapper;
import com.fasterxml.jackson.databind.jsontype.impl.laissezfairesubtypevalidator;
import com.gitee.ccsert.mall.common.redis.redisservice;
import com.gitee.ccsert.mall.common.redis.impl.redisserviceimpl;
import org.springframework.context.annotation.bean;
import org.springframework.data.redis.cache.rediscacheconfiguration;
import org.springframework.data.redis.cache.rediscachemanager;
import org.springframework.data.redis.cache.rediscachewriter;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.serializer.jackson2jsonredisserializer;
import org.springframework.data.redis.serializer.redisserializationcontext;
import org.springframework.data.redis.serializer.redisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;

import java.time.duration;

/**
 * classname: redisconfig <br/>
 * description: redis连接配置类 <br/>
 */
@configuration
public class baseredisconfig {
    @bean
    public redistemplate<string, object> redistemplate(redisconnectionfactory redisconnectionfactory) {
        redisserializer<object> serializer = redisserializer();
        redistemplate<string, object> redistemplate = new redistemplate<>();
        redistemplate.setconnectionfactory(redisconnectionfactory);
        redistemplate.setkeyserializer(new stringredisserializer());
        redistemplate.setvalueserializer(serializer);
        redistemplate.sethashkeyserializer(new stringredisserializer());
        redistemplate.sethashvalueserializer(serializer);
        redistemplate.afterpropertiesset();
        return redistemplate;
    }

    @bean
    public redisserializer<object> redisserializer() {

        //创建json序列化器
        jackson2jsonredisserializer<object> serializer = new jackson2jsonredisserializer<>(object.class);
        objectmapper objectmapper = new objectmapper();
        objectmapper.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
        //必须设置,否则无法将json转化为对象,会转化成map类型
        objectmapper.activatedefaulttyping(laissezfairesubtypevalidator.instance,objectmapper.defaulttyping.non_final);
        serializer.setobjectmapper(objectmapper);
        return serializer;
    }
    @bean
    public rediscachemanager rediscachemanager(redisconnectionfactory redisconnectionfactory) {
        rediscachewriter rediscachewriter = rediscachewriter.nonlockingrediscachewriter(redisconnectionfactory);
        //设置redis缓存有效期为1天
        rediscacheconfiguration rediscacheconfiguration = rediscacheconfiguration.defaultcacheconfig()
                .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(redisserializer())).entryttl(duration.ofdays(1));
        return new rediscachemanager(rediscachewriter, rediscacheconfiguration);
    }
    @bean
    public redisservice redisservice(){
        return new redisserviceimpl();
    }
}

接口

package com.gitee.ccsert.mall.common.redis;

import org.springframework.data.domain.sort;
import org.springframework.data.geo.distance;
import org.springframework.data.geo.georesults;
import org.springframework.data.geo.point;
import org.springframework.data.redis.connection.redisgeocommands;

import java.util.list;
import java.util.map;
import java.util.set;

/**
 * classname: redisservice <br/>
 * description: redis操作接口 <br/>
 */
public interface redisservice {
    /**
     * 保存属性
     *
     * @param key   key值
     * @param value value值
     * @param time  时间戳
     */
    void set(string key, object value, long time);

    /**
     * 保存属性
     *
     * @param key   key值
     * @param value value值
     */
    void set(string key, object value);

    /**
     * 获取属性
     *
     * @param key key值
     * @return 返回对象
     */
    object get(string key);

    /**
     * 删除属性
     *
     * @param key key值
     * @return 返回成功
     */
    boolean del(string key);

    /**
     * 批量删除属性
     *
     * @param keys key值集合
     * @return 返回删除数量
     */
    long del(list<string> keys);

    /**
     * 设置过期时间
     *
     * @param key  key值
     * @param time 时间戳
     * @return 返回成功
     */
    boolean expire(string key, long time);

    /**
     * 获取过期时间
     *
     * @param key key值
     * @return 返回时间戳
     */
    long getexpire(string key);

    /**
     * 判断key是否存在
     *
     * @param key key值
     * @return 返回
     */
    boolean haskey(string key);

    /**
     * 按delta递增
     *
     * @param key   key值
     * @param delta delta值
     * @return 返回递增后结果
     */
    long incr(string key, long delta);

    /**
     * 按delta递减
     *
     * @param key   key值
     * @param delta delta值
     * @return 返回递减后结果
     */
    long decr(string key, long delta);

    /**
     * 获取hash结构中的属性
     *
     * @param key     外部key值
     * @param hashkey 内部key值
     * @return 返回内部key的value
     */
    object hget(string key, string hashkey);

    /**
     * 向hash结构中放入一个属性
     *
     * @param key     外部key
     * @param hashkey 内部key
     * @param value   内部key的value
     * @param time    过期时间
     * @return 返回是否成功
     */
    boolean hset(string key, string hashkey, object value, long time);

    /**
     * 向hash结构中放入一个属性
     *
     * @param key     外部key
     * @param hashkey 内部key
     * @param value   内部key的value
     */
    void hset(string key, string hashkey, object value);

    /**
     * 直接获取整个hash结构
     *
     * @param key 外部key值
     * @return 返回hashmap
     */
    map<object, object> hgetall(string key);

    /**
     * 直接设置整个hash结构
     *
     * @param key  外部key
     * @param map  hashmap值
     * @param time 过期时间
     * @return 返回是否成功
     */
    boolean hsetall(string key, map<string, object> map, long time);

    /**
     * 直接设置整个hash结构
     *
     * @param key 外部key
     * @param map hashmap值
     */
    void hsetall(string key, map<string, ?> map);

    /**
     * 删除hash结构中的属性
     *
     * @param key     外部key值
     * @param hashkey 内部key值
     */
    void hdel(string key, object... hashkey);

    /**
     * 判断hash结构中是否有该属性
     *
     * @param key     外部key
     * @param hashkey 内部key
     * @return 返回是否存在
     */
    boolean hhaskey(string key, string hashkey);

    /**
     * hash结构中属性递增
     *
     * @param key     外部key
     * @param hashkey 内部key
     * @param delta   递增条件
     * @return 返回递增后的数据
     */
    long hincr(string key, string hashkey, long delta);

    /**
     * hash结构中属性递减
     *
     * @param key     外部key
     * @param hashkey 内部key
     * @param delta   递增条件
     * @return 返回递减后的数据
     */
    long hdecr(string key, string hashkey, long delta);

    /**
     * 获取set结构
     *
     * @param key key
     * @return 返回set集合
     */
    set<object> smembers(string key);

    /**
     * 向set结构中添加属性
     *
     * @param key    key
     * @param values value集
     * @return 返回增加数量
     */
    long sadd(string key, object... values);

    /**
     * 向set结构中添加属性
     *
     * @param key    key
     * @param time   过期时间
     * @param values 值集合
     * @return 返回添加的数量
     */
    long sadd(string key, long time, object... values);

    /**
     * 是否为set中的属性
     *
     * @param key   key
     * @param value value
     * @return 返回是否存在
     */
    boolean sismember(string key, object value);

    /**
     * 获取set结构的长度
     *
     * @param key key
     * @return 返回长度
     */
    long ssize(string key);

    /**
     * 删除set结构中的属性
     *
     * @param key    key
     * @param values value集合
     * @return 删除掉的数据量
     */
    long sremove(string key, object... values);

    /**
     * 获取list结构中的属性
     *
     * @param key   key
     * @param start 开始
     * @param end   结束
     * @return 返回查询的集合
     */
    list<object> lrange(string key, long start, long end);

    /**
     * 获取list结构的长度
     *
     * @param key key
     * @return 长度
     */
    long lsize(string key);

    /**
     * 根据索引获取list中的属性
     *
     * @param key   key
     * @param index 索引
     * @return 对象
     */
    object lindex(string key, long index);

    /**
     * 向list结构中添加属性
     *
     * @param key   key
     * @param value value
     * @return 增加后的长度
     */
    long lpush(string key, object value);

    /**
     * 向list结构中添加属性
     *
     * @param key   key
     * @param value value
     * @param time  过期时间
     * @return 增加后的长度
     */
    long lpush(string key, object value, long time);

    /**
     * 向list结构中批量添加属性
     *
     * @param key    key
     * @param values value 集合
     * @return 增加后的长度
     */
    long lpushall(string key, object... values);

    /**
     * 向list结构中批量添加属性
     *
     * @param key    key
     * @param time   过期时间
     * @param values value集合
     * @return 增加后的长度
     */
    long lpushall(string key, long time, object... values);

    /**
     * 从list结构中移除属性
     *
     * @param key   key
     * @param count 总量
     * @param value value
     * @return 返回删除后的长度
     */
    long lremove(string key, long count, object value);

    /**
     * 向bitmap中新增值
     *
     * @param key    key
     * @param offset 偏移量
     * @param b      状态
     * @return 结果
     */
    boolean bitadd(string key, int offset, boolean b);

    /**
     * 从bitmap中获取偏移量的值
     *
     * @param key    key
     * @param offset 偏移量
     * @return 结果
     */
    boolean bitget(string key, int offset);

    /**
     * 获取bitmap的key值总和
     *
     * @param key key
     * @return 总和
     */
    long bitcount(string key);

    /**
     * 获取bitmap范围值
     *
     * @param key    key
     * @param limit  范围
     * @param offset 开始偏移量
     * @return long类型集合
     */
    list<long> bitfield(string key, int limit, int offset);

    /**
     * 获取所有bitmap
     *
     * @param key key
     * @return 以二进制字节数组返回
     */
    byte[] bitgetall(string key);

    /**
     * 增加坐标
     *
     * @param key  key
     * @param x    x
     * @param y    y
     * @param name 地点名称
     * @return 返回结果
     */
    long geoadd(string key, double x, double y, string name);

    /**
     * 根据城市名称获取坐标集合
     *
     * @param key   key
     * @param place 地点
     * @return 坐标集合
     */
    list<point> geogetpointlist(string key, object... place);

    /**
     * 计算两个城市之间的距离
     *
     * @param key      key
     * @param placeone 地点1
     * @param placetow 地点2
     * @return 返回距离
     */
    distance geocalculationdistance(string key, string placeone, string placetow);

    /**
     * 获取附该地点附近的其他地点
     *
     * @param key      key
     * @param place    地点
     * @param distance 附近的范围
     * @param limit    查几条
     * @param sort     排序规则
     * @return 返回附近的地点集合
     */
    georesults<redisgeocommands.geolocation<object>> geonearbyplace(string key, string place, distance distance, long limit, sort.direction sort);

    /**
     * 获取地点的hash
     *
     * @param key   key
     * @param place 地点
     * @return 返回集合
     */
    list<string> geogethash(string key, string... place);
}

实现

package com.gitee.ccsert.mall.common.redis.impl;

import com.gitee.ccsert.mall.common.redis.redisservice;
import org.springframework.data.domain.sort;
import org.springframework.data.geo.distance;
import org.springframework.data.geo.georesults;
import org.springframework.data.geo.point;
import org.springframework.data.redis.connection.bitfieldsubcommands;
import org.springframework.data.redis.connection.redisgeocommands;
import org.springframework.data.redis.core.rediscallback;
import org.springframework.data.redis.core.redistemplate;

import javax.annotation.resource;
import java.util.list;
import java.util.map;
import java.util.set;
import java.util.concurrent.timeunit;

/**
 * classname: redisserviceimpl <br/>
 * description: redis操作的具体时间类 <br/>
 */
public class redisserviceimpl implements redisservice {
    @resource
    private redistemplate<string, object> redistemplate;

    @override
    public void set(string key, object value, long time) {
        redistemplate.opsforvalue().set(key, value, time, timeunit.seconds);
    }

    @override
    public void set(string key, object value) {
        redistemplate.opsforvalue().set(key, value);
    }

    @override
    public object get(string key) {
        return redistemplate.opsforvalue().get(key);
    }

    @override
    public boolean del(string key) {
        return redistemplate.delete(key);
    }

    @override
    public long del(list<string> keys) {
        return redistemplate.delete(keys);
    }

    @override
    public boolean expire(string key, long time) {
        return redistemplate.expire(key, time, timeunit.seconds);
    }

    @override
    public long getexpire(string key) {
        return redistemplate.getexpire(key, timeunit.seconds);
    }

    @override
    public boolean haskey(string key) {
        return redistemplate.haskey(key);
    }

    @override
    public long incr(string key, long delta) {
        return redistemplate.opsforvalue().increment(key, delta);
    }

    @override
    public long decr(string key, long delta) {
        return redistemplate.opsforvalue().increment(key, -delta);
    }

    @override
    public object hget(string key, string hashkey) {
        return redistemplate.opsforhash().get(key, hashkey);
    }

    @override
    public boolean hset(string key, string hashkey, object value, long time) {
        redistemplate.opsforhash().put(key, hashkey, value);
        return expire(key, time);
    }

    @override
    public void hset(string key, string hashkey, object value) {
        redistemplate.opsforhash().put(key, hashkey, value);
    }

    @override
    public map<object, object> hgetall(string key) {
        return redistemplate.opsforhash().entries(key);
    }

    @override
    public boolean hsetall(string key, map<string, object> map, long time) {
        redistemplate.opsforhash().putall(key, map);
        return expire(key, time);
    }

    @override
    public void hsetall(string key, map<string, ?> map) {
        redistemplate.opsforhash().putall(key, map);
    }

    @override
    public void hdel(string key, object... hashkey) {
        redistemplate.opsforhash().delete(key, hashkey);
    }

    @override
    public boolean hhaskey(string key, string hashkey) {
        return redistemplate.opsforhash().haskey(key, hashkey);
    }

    @override
    public long hincr(string key, string hashkey, long delta) {
        return redistemplate.opsforhash().increment(key, hashkey, delta);
    }

    @override
    public long hdecr(string key, string hashkey, long delta) {
        return redistemplate.opsforhash().increment(key, hashkey, -delta);
    }

    @override
    public set<object> smembers(string key) {
        return redistemplate.opsforset().members(key);
    }

    @override
    public long sadd(string key, object... values) {
        return redistemplate.opsforset().add(key, values);
    }

    @override
    public long sadd(string key, long time, object... values) {
        long count = redistemplate.opsforset().add(key, values);
        expire(key, time);
        return count;
    }

    @override
    public boolean sismember(string key, object value) {
        return redistemplate.opsforset().ismember(key, value);
    }

    @override
    public long ssize(string key) {
        return redistemplate.opsforset().size(key);
    }

    @override
    public long sremove(string key, object... values) {
        return redistemplate.opsforset().remove(key, values);
    }

    @override
    public list<object> lrange(string key, long start, long end) {
        return redistemplate.opsforlist().range(key, start, end);
    }

    @override
    public long lsize(string key) {
        return redistemplate.opsforlist().size(key);
    }

    @override
    public object lindex(string key, long index) {
        return redistemplate.opsforlist().index(key, index);
    }

    @override
    public long lpush(string key, object value) {
        return redistemplate.opsforlist().rightpush(key, value);
    }

    @override
    public long lpush(string key, object value, long time) {
        long index = redistemplate.opsforlist().rightpush(key, value);
        expire(key, time);
        return index;
    }

    @override
    public long lpushall(string key, object... values) {
        return redistemplate.opsforlist().rightpushall(key, values);
    }

    @override
    public long lpushall(string key, long time, object... values) {
        long count = redistemplate.opsforlist().rightpushall(key, values);
        expire(key, time);
        return count;
    }

    @override
    public long lremove(string key, long count, object value) {
        return redistemplate.opsforlist().remove(key, count, value);
    }

    @override
    public boolean bitadd(string key, int offset, boolean b) {
        return redistemplate.opsforvalue().setbit(key, offset, b);
    }

    @override
    public boolean bitget(string key, int offset) {
        return redistemplate.opsforvalue().getbit(key, offset);
    }

    @override
    public long bitcount(string key) {
        return redistemplate.execute((rediscallback<long>) con -> con.bitcount(key.getbytes()));
    }

    @override
    public list<long> bitfield(string key, int limit, int offset) {
        return redistemplate.execute((rediscallback<list<long>>) con ->
                con.bitfield(key.getbytes(),
                        bitfieldsubcommands.create().get(bitfieldsubcommands.bitfieldtype.unsigned(limit)).valueat(offset)));
    }

    @override
    public byte[] bitgetall(string key) {
        return redistemplate.execute((rediscallback<byte[]>) con -> con.get(key.getbytes()));
    }

    @override
    public long geoadd(string key, double x, double y, string name) {
        return redistemplate.opsforgeo().add(key, new point(x, y), name);
    }

    @override
    public list<point> geogetpointlist(string key, object... place) {
        return redistemplate.opsforgeo().position(key, place);
    }

    @override
    public distance geocalculationdistance(string key, string placeone, string placetow) {
        return redistemplate.opsforgeo()
                .distance(key, placeone, placetow, redisgeocommands.distanceunit.kilometers);
    }

    @override
    public georesults<redisgeocommands.geolocation<object>> geonearbyplace(string key, string place, distance distance, long limit, sort.direction sort) {
        redisgeocommands.georadiuscommandargs args = redisgeocommands.georadiuscommandargs.newgeoradiusargs().includedistance().includecoordinates();
        // 判断排序方式
        if (sort.direction.asc == sort) {
            args.sortascending();
        } else {
            args.sortdescending();
        }
        args.limit(limit);
        return redistemplate.opsforgeo()
                .radius(key, place, distance, args);
    }

    @override
    public list<string> geogethash(string key, string... place) {
        return redistemplate.opsforgeo()
                .hash(key, place);
    }

}

《RedisTemplate常用方法封装.doc》

下载本文的Word格式文档,以方便收藏与打印。