百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

springboot-data-redis-应用

yuyutoo 2024-12-12 15:54 1 浏览 0 评论

封装redisTemplate工具类

package com.hfw.basesystem.config;

import javax.annotation.Resource;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.data.redis.domain.geo.GeoShape;
import org.springframework.scripting.support.StaticScriptSource;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * 官方命令文档:https://redis.io/commands/
 * @author farkle
 * @create 2020-04-25
 */
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    //@Resource
    //private StringRedisTemplate stringRedisTemplate;

    /*************************string操作*****************************/
    /*public void setStr(String key, String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }
    public String getStr(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }*/

    public <T> T get(String key) {
        return (T)redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取并设置过期时间
     * @param key
     * @param expire
     * @param <T>
     * @return
     */
    public <T> T getEx(String key, long expire){
        return (T)redisTemplate.opsForValue().getAndExpire(key, expire, TimeUnit.SECONDS);
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置值和超时事件
     * @param key
     * @param value
     * @param expire
     */
    public void setEx(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
    }

    /**
     * key不存在时设置
     * @param key
     * @param value
     * @return
     */
    public Boolean setNx(String key, Object value){
        return redisTemplate.opsForValue().setIfAbsent(key,value);
    }

    /**
     * key存在时设置
     * @param key
     * @param value
     * @return
     */
    public Boolean setXx(String key, Object value){
        return redisTemplate.opsForValue().setIfPresent(key,value);
    }
    public Boolean setNxEx(String key, Object value, long timeout){
        return redisTemplate.opsForValue().setIfAbsent(key,value, timeout, TimeUnit.SECONDS);
    }
    /*public Boolean setNxEx(String key, Object value, long expire) {
        return redisTemplate.execute((RedisConnection redisConnection) ->
                redisConnection.set(key.getBytes(), value.getBytes(), Expiration.from(expire, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT)
        );
    }*/
    public <T> T getSet(String key, Object value){
        return (T)redisTemplate.opsForValue().getAndSet(key, value);
    }

    public Boolean expire(String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    public Boolean exists(String key){
        return redisTemplate.hasKey(key);
    }
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }
    public Long del(Collection<String> keys) {
        return redisTemplate.delete(keys);
    }

    public Long incr(String key) {
        return redisTemplate.opsForValue().increment(key);
    }
    public Long decr(String key){
        return redisTemplate.opsForValue().decrement(key);
    }

    /**
     *************************list操作*****************************
     * 有序,可重复
     * 1、作为栈或队列使用
     * 2、可用于各种列表,比如用户列表、商品列表、评论列表等。
     */

    /**
     * 从列表头部插入
     * @param key
     * @param value
     * @return 返回列表的长度
     */
    public Long lPush(String key, Object value){
        return redisTemplate.opsForList().leftPush(key, value);
    }
    public <T> T lPop(String key){
        return (T) redisTemplate.opsForList().leftPop(key);
    }
    public Long rPush(String key, Object value){
        return redisTemplate.opsForList().rightPush(key, value);
    }
    public <T> T rPop(String key){
        return (T) redisTemplate.opsForList().rightPop(key);
    }

    /**
     * 当列表为空时阻塞
     * @param key
     * @param timeout 设置最大阻塞时间
     * @param <T>
     * @return
     */
    public <T> T bLPop(String key, long timeout){
        return (T) redisTemplate.opsForList().leftPop(key, timeout, TimeUnit.SECONDS);
    }
    public <T> T bRPop(String key, long timeout){
        return (T) redisTemplate.opsForList().rightPop(key, timeout, TimeUnit.SECONDS);
    }
    public Long lLen(String key){
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 获取指定索引的元素
     * @param key
     * @param index 索引,从0开始
     * @param <T>
     * @return
     */
    public <T> T lIndex(String key, long index){
        return (T) redisTemplate.opsForList().index(key, index);
    }
    public <T> List<T> lRange(String key, long start, long end){
        return (List<T>) redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 从列表中删除元素
     * @param key
     * @param value 要删除的元素
     * @return
     */
    public Long lRem(String key, Object value){
        /**
         * count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT
         * count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值
         * count = 0 : 移除表中所有与 VALUE 相等的值
         */
        return redisTemplate.opsForList().remove(key,0, value);
    }

    /**
     * 设置列表中指定索引的值
     * @param key
     * @param index 索引
     * @param value 值
     */
    public void lSet(String key, long index, Object value){
        redisTemplate.opsForList().set(key,index,value);
    }

    /**
     * 对列表进行修剪,只保留start到end区间
     * @param key
     * @param start
     * @param end
     */
    public void lTrim(String key, long start, long end){
        redisTemplate.opsForList().trim(key,start,end);
    }
    public <T> T rPopLPush(String sourceKey, String destinationKey){
        return (T) redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey);
    }
    //会阻塞
    public <T> T bRPopLPush(String sourceKey, String destinationKey, long timeout){
        return (T) redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout,TimeUnit.SECONDS);
    }

    /**
     * 将value插入到列表,且位于值pivot之前
     * @param key
     * @param pivot
     * @param value
     * @return
     */
    public Long lInsert(String key, Object pivot, Object value){
        return redisTemplate.opsForList().leftPush(key,pivot,value);
    }

    /**
     **************************set操作*****************************
     * 无序,不重复
     * 适用于不能重复的且不需要顺序的数据结构, 比如:关注的用户,还可以通过spop进行随机抽奖
     */

    public Long sAdd(String key, Object ... values){
        return redisTemplate.opsForSet().add(key, values);
    }
    public Long sRem(String key, Object ... values){
        return redisTemplate.opsForSet().remove(key, values);
    }
    public <T> Set<T> sMembers(String key){
        return (Set<T>) redisTemplate.opsForSet().members(key);
    }

    /**
     * 随机弹出一个元素,删除
     * @param key
     * @param <T>
     * @return
     */
    public <T> T sPop(String key){
        return (T) redisTemplate.opsForSet().pop(key);
    }

    /**
     * 随机获取一个元素,不删除
     * @param key
     * @param <T>
     * @return
     */
    public <T> T sRandMember(String key){
        return (T) redisTemplate.opsForSet().randomMember(key);
    }

    /**
     * 获取数量
     * @param key
     * @return
     */
    public Long sCard(String key){
        return redisTemplate.opsForSet().size(key);
    }

    /**
     * 是否在集合内
     * @param key
     * @param member
     * @return
     */
    public Boolean sIsMember(String key, Object member){
        return redisTemplate.opsForSet().isMember(key, member);
    }

    /**
     * 求两个集合的交集
     * @param key
     * @param anotherKey
     * @param <T>
     * @return
     */
    public <T> Set<T> sInter(String key, String anotherKey){
        return (Set<T>) redisTemplate.opsForSet().intersect(key, anotherKey);
    }

    /**
     * 求两个集合的差集
     * @param key
     * @param anotherKey
     * @param <T>
     * @return
     */
    public <T> Set<T> sDiff(String key, String anotherKey){
        return (Set<T>) redisTemplate.opsForSet().difference(key, anotherKey);
    }

    /**
     * 求两个集合的并集
     * @param key
     * @param anotherKey
     * @param <T>
     * @return
     */
    public <T> Set<T> sUnion(String key, String anotherKey){
        return (Set<T>) redisTemplate.opsForSet().union(key, anotherKey);
    }

    /**
     **************************zset操作*****************************
     * 有序,不重复,且每一个元素关联一个score
     * 由于可以按照分值排序,所以适用于各种排行榜。比如:点击排行榜、销量排行榜、关注排行榜等
     */

    public Boolean zAdd(String key, Object value, double score){
        return redisTemplate.opsForZSet().add(key,value,score);
    }
    public Long zRem(String key, Object... values){
        return redisTemplate.opsForZSet().remove(key, values);
    }

    /**
     * 获取集合数量
     * @param key
     * @return
     */
    public Long zCard(String key){
        return redisTemplate.opsForZSet().zCard(key);
    }

    /**
     * 返回集合中score值在[min,max]区间
     * 的元素数量
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Long zCount(String key, double min, double max){
        return redisTemplate.opsForZSet().count(key, min, max);
    }

    /**
     * 集合的元素分值增加
     * @param key
     * @param value
     * @param delta
     * @return
     */
    public Double zIncrBy(String key, Object value, double delta){
        return redisTemplate.opsForZSet().incrementScore(key,value,delta);
    }

    /**
     * 获取指定元素的分值
     * @param key
     * @param value
     * @return
     */
    public Double zScore(String key, Object value){
        return redisTemplate.opsForZSet().score(key,value);
    }

    /**
     * 获取指定元素的分值排行榜(升序,分值从小到大)
     * @param key
     * @param value
     * @return
     */
    public Long zrank(String key, Object value){
        return redisTemplate.opsForZSet().rank(key, value);
    }

    /**
     *  获取指定元素的分值排行榜(降序,分值从大到小)
     * @param key
     * @param value
     * @return
     */
    public Long zRevRank(String key, Object value){
        return redisTemplate.opsForZSet().reverseRank(key,value);
    }

    /**
     * 按索引获取集合中的数据(升序)
     * @param key
     * @param start
     * @param end
     * @param <T>
     * @return
     */
    public <T> Set<T> zRange(String key, long start, long end){
        return (Set<T>) redisTemplate.opsForZSet().range(key, start, end);
    }
    public <T> Set<T> zRevRange(String key, long start, long end){
        return (Set<T>) redisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    /**
     * 按索引获取集合中的数据及分数(升序)
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<ZSetOperations.TypedTuple<Object>> zRangeWithScores(String key, long start, long end){
        return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    /**
     * 根据分值获取集合中的数据(升序)
     * @param key
     * @param min
     * @param max
     * @param <T>
     * @return
     */
    public <T> Set<T> zRangeByScore(String key, double min, double max){
        return (Set<T>) redisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    /**
     *************************hash操作*****************************
     * 应用场景: 对象的存储 ,表数据的映射
     */

    /**
     * 设置对象的 一个字段
     * @param key 对象主键
     * @param hashKey 对象字段
     * @param hashValue 对象主键值
     */
    public void hSet(String key, String hashKey, Object hashValue){
        redisTemplate.opsForHash().put(key, hashKey, hashValue);
    }
    public void hMSet(String key, Map<String,Object> data){
        redisTemplate.opsForHash().putAll(key,data);
    }

    /**
     * hashKey不存在时设置 hashKey的值
     * @param key
     * @param hashKey
     * @param hashValue
     * @return
     */
    public Boolean hSetNX(String key, String hashKey, Object hashValue){
        return redisTemplate.opsForHash().putIfAbsent(key, hashKey,hashValue);
    }

    /**
     * 查看对象的 某个字段是否存在
     * @param key 对象主键
     * @param hashKey 对象字段
     * @return
     */
    public Boolean hExists(String key, String hashKey){
        return redisTemplate.opsForHash().hasKey(key,hashKey);
    }

    /**
     * 获取对象的某个字段值
     * @param key 对象主键
     * @param hashKey 对象字段
     * @param <T>
     * @return
     */
    public <T> T hGet(String key, String hashKey){
        return (T) redisTemplate.opsForHash().get(key, hashKey);
    }
    public List hMGet(String key, Collection hashKeys){
        return redisTemplate.opsForHash().multiGet(key, hashKeys);
    }

    /**
     * 删除对象的某个字段
     * @param key 对象主键
     * @param value 对象字段
     */
    public Long hDel(String key, Object... value){
        return redisTemplate.opsForHash().delete(key, value);
    }

    /**
     * 获取对象的字段个数
     * @param key
     * @return
     */
    public Long hLen(String key){
        return redisTemplate.opsForHash().size(key);
    }

    /**
     **************************bitmap操作*****************************
     * 应用:用户每月签到,用户id为key , 日期作为偏移量 1表示签到
     */

    public Boolean setBit(String key, long offset, boolean value){
        return redisTemplate.opsForValue().setBit(key,offset,value);
    }
    /*public void setBit(String key, long offset, boolean value) {
        stringRedisTemplate.execute((RedisConnection redisConnection) -> {
            try {
                return redisConnection.setBit((key).getBytes("UTF-8"), offset, value);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        });
    }*/
    public Boolean getBit(String key, long offset) {
        return redisTemplate.opsForValue().getBit(key,offset);
    }

    /**
     **************************GEO地理位置操作*****************************
     * 应用:附件的人,计算距离
     */

    /**
     * 添加坐标点
     * @param key
     * @param point
     * @param value
     * @return
     */
    public Long geoAdd(String key, Point point, Object value){
        return redisTemplate.boundGeoOps(key).add(point, value);
    }

    /**
     * 获取geo成员的坐标
     * @param key
     * @param members
     * @return
     */
    public List<Point> geoPos(String key, Object... members){
        return redisTemplate.boundGeoOps(key).position(members);
    }

    /**
     * 计算两个点的距离
     * @param key
     * @param o1 点1的值
     * @param o2 点2的值
     * @return
     */
    public Distance geoDist(String key,Object o1,Object o2){
        return redisTemplate.boundGeoOps(key).distance(o1,o2);
    }
    /**
     * 中心点搜索
     * @param key
     * @param point 中心点
     * @param distance 半径
     * @param count 数量
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoRadius(String key, Point point, Distance distance, long count){
        Circle circle = new Circle(point,distance);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending().limit(count);
        return redisTemplate.boundGeoOps(key).radius(circle, args);
    }

    /**
     * 成员做中心点搜索
     * @param key
     * @param member 成员
     * @param distance 半径
     * @param count 数量
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoRadiusByMember(String key, Object member,Distance distance, long count){
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending().limit(count);
        return redisTemplate.boundGeoOps(key).radius(member, distance, args);
    }

    /**
     * 根据值删除坐标点
     * @param key
     * @param value
     * @return
     */
    public Long geoRemove(String key, Object value){
        return redisTemplate.boundGeoOps(key).remove(value);
        //return this.zrem(key,value); //GEO数据是保存在zset中的,所以可以通过zset的命令删除
    }

    /**
     * 中心点搜索并存储成zset
     * @param key
     * @param zsetKey 存储的zset_key
     * @param point 中心点
     * @param distance 半径
     * @param count 数量
     * @return
     */
    public Long geoSearchStore(String key, String zsetKey, Point point, Distance distance, long count){
        RedisGeoCommands.GeoSearchStoreCommandArgs args = RedisGeoCommands.GeoSearchStoreCommandArgs.newGeoSearchStoreArgs().storeDistance().sortAscending().limit(count);
        return redisTemplate.boundGeoOps(key).searchAndStore(zsetKey, GeoReference.fromCoordinate(point), GeoShape.byRadius(distance), args);
    }



    /*************************布隆过滤器操作*****************************/
    /**
     * 布隆过滤器-添加
     * 可用于把消息置为已读
     *
     * @param key
     * @param value
     * @return
     */
    public Long bfAdd(String key, String value) {
        DefaultRedisScript<Long> script = new DefaultRedisScript();
        script.setResultType(Long.class);
        script.setScriptSource(new StaticScriptSource("return redis.call('bf.add', KEYS[1], KEYS[2])"));
        return redisTemplate.execute(script, Arrays.asList(key, value));
    }

    /**
     * 布隆过滤器-判断
     * 可用于获取消息的状态
     * @param key
     * @param value
     * @return
     */
    public Boolean bfExists(String key, String value) {
        DefaultRedisScript<Long> script = new DefaultRedisScript();
        script.setResultType(Long.class);
        script.setScriptSource(new StaticScriptSource("return redis.call('bf.exists', KEYS[1], KEYS[2])"));
        Long res = redisTemplate.execute(script, Arrays.asList(key, value));
        return 1 == res;
    }

    /**
     * 布隆过滤器-设置存储空间和错误率
     * error_rate, initial_size,错误率越低,需要的空间越大,error_rate表示预计错误率,initial_size参数表示预计放入的元素数量,当实际数量超过这个值时,误判率会上升,所以需要提前设置一个较大的数值来避免超出
     * @param key
     * @param count 空间大小
     * @return
     */
    public Boolean bfReserve(String key, Long count) {
        String cnt = count > 100 ? count + "" : "100";
        String errorRate = new BigDecimal(cnt).divide(new BigDecimal(10000)).toString();
        DefaultRedisScript<String> script = new DefaultRedisScript();
        script.setResultType(String.class);
        script.setScriptSource(new StaticScriptSource("return redis.call('bf.reserve', KEYS[1], KEYS[2], KEYS[3])"));
        String res = redisTemplate.execute(script, Arrays.asList(key, errorRate, cnt));
        return "OK".equals(res);
    }

}

rediskey的设计

  1. 用:分割
  2. 把表名转换为key前缀, 比如: user:
  3. 第二段放置主键值
  4. 第三段放置列名或忽略
  5. 示例: 用户表---> user:1

基于redis实现登录认证

redis数据结构设计

sysuser_token:token  string类型存储用户登录信息
sysuser_token_list:userId	 list结构存储用户的所有token
1. 用户登录
	生成token, 并存储 sysuser_token:token 用户登录信息
  向sysuser_token_list:userId入栈生成的token, 如果超出同一用户最大登录限制, 则出栈一条token
	出栈的token判断是否有效, 有效则删除对应的sysuser_token:token(被挤下线)
2. 根据token校验用户信息
	直接获取sysuser_token:token存储的用户信息, 存在且充值超时时间
3. 用户登出
	删除sysuser_token_list:userId
  删除sysuser_token_list:userId 中存储的所有token
 4. 禁用用户
 	-->用户登出. 重新登录时判断是否被禁用
 	-->或者修改sysuser_token_list:userId 中存储的所有token对应用户的禁用字段标识

代码实现

package com.hfw.basesystem.service.impl;

import com.hfw.basesystem.config.RedisUtil;
import com.hfw.basesystem.service.RedisAuthService;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * redis认证服务
 * @author farkle
 * @date 2023-02-02
 */
//@Service("redisAuthService")
public class RedisAuthServiceImpl implements RedisAuthService {
    /**
     * 限制同一账号最大登录人数
     */
    private int max_login = 2;

    /**
     * token前缀
     */
    private String token_key_prefix;
    /**
     * 存储所有登录的token前缀
     */
    private String user_token_list_prefix;

    /**
     * 失效时间
     * 30分钟(单位秒)
     */
    private long expire = 30*60;

    private RedisUtil redisUtil;

    public void setMax_login(int max_login) {
        this.max_login = max_login;
    }

    public void setToken_key_prefix(String token_key_prefix) {
        this.token_key_prefix = token_key_prefix;
    }

    public void setUser_token_list_prefix(String user_token_list_prefix) {
        this.user_token_list_prefix = user_token_list_prefix;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public String genToken(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

	//用户登录时存储登录信息
    @Override
    public String store(Long userId, String token, Object obj){
        String userTokenListKey = user_token_list_prefix + userId;
        Long userTokenSize = redisUtil.lPush(userTokenListKey, token);
        redisUtil.setEx(token_key_prefix+ token, obj, expire);
        if(userTokenSize > max_login){
            String rpop = redisUtil.rPop(userTokenListKey);
            if(this.exists(rpop)){
                this.logout(rpop);
                return rpop;
            }
        }
        return null;
    }

//更新登录信息
    @Override
    public int update(Long userId, Object obj){
        List<String> tokenList = redisUtil.lRange(user_token_list_prefix + userId, 0, max_login);
        if(CollectionUtils.isEmpty(tokenList)){
            return 0;
        }
        int cnt = 0;
        for(String token : tokenList){
            if( redisUtil.setXx(token_key_prefix+token, obj) ){
                cnt++;
            }
        }
        return cnt;
    }
    /**
     * 判断token是否存在
     * @param token
     * @return
     */
    @Override
    public Boolean exists(String token){
        return redisUtil.exists(token_key_prefix+token);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    @Override
    public <T> T validToken(String token){
        return redisUtil.getEx(token_key_prefix+ token, expire);
    }

    @Override
    public List<String> getValidToken(Long userId){
        List<String> tokenList = redisUtil.lRange(user_token_list_prefix + userId, 0, max_login);
        List<String> validList = tokenList.stream().filter(token -> this.exists(token)).collect(Collectors.toList());
        return validList;
    }

    /**
     * 用户登出
     * @param userId
     */
    @Override
    public Boolean logout(Long userId){
        List<String> tokenList = redisUtil.lRange(user_token_list_prefix + userId, 0, max_login);
        if(CollectionUtils.isEmpty(tokenList)){
            return false;
        }
        List<String> keys = tokenList.stream().map(token -> token_key_prefix + token).collect(Collectors.toList());
        Long dels = redisUtil.del(keys);
        redisUtil.del(user_token_list_prefix+userId);
        return dels>0;
    }
    /**
     * 当前token登出
     * @param token
     */
    @Override
    public Boolean logout(String token){
        return redisUtil.del(token_key_prefix+ token);
    }
    /**
     * 禁用用户
     * @param userId
     * @return
     */
    @Override
    public Boolean disableUser(Long userId){
        return this.logout(userId);
    }

}

基于redis实现附近的人

实现思路

  1. 基于GEO地理位置实现
  2. 用geoAdd命令添加坐标点
  3. 用geoSearchStore命令搜索附近的点并存储成zset(距离做score. 方便分页查找). 当查询的数量不满足前端浏览量时扩大搜索半径.
  4. 用zRange WithScores命令对附近的点进行分页查询给前端展示.

实现代码

package com.hfw.basesystem.service.impl;

import com.hfw.basesystem.config.RedisUtil;
import com.hfw.basesystem.service.RedisGeoService;
import com.hfw.common.entity.PageResult;
import com.hfw.common.util.NumberUtil;
import javax.annotation.Resource;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author farkle
 * @date 2022-11-27
 */
@Service("redisGeoService")
public class RedisGeoServiceImpl implements RedisGeoService {
    /**
     * 附近的点最多获取多少个
     */
    private static final Integer max_count = 10000;
    private static final Integer min_count = 100;
    /**
     * 附近的点最大半径距离,单位米
     */
    private static final Integer max_distance = 1000*1000;
    /**
     * 附近的点实现zset key
     */
    private static final String near_zset_key = "near_zset";
    public static final String near_geo_key = "near_geo";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Set<ZSetOperations.TypedTuple<Object>> near(double lng, double lat, Integer pageNumber, Integer pageSize){
        PageResult page = new PageResult(pageNumber, pageSize);
        Integer requestCount = page.getEnd()+1;
        if(pageNumber>1 && requestCount>max_count){
            return null;
        }
        Integer searchCount = min_count;
        int i = 0;
        while (searchCount<max_count && searchCount<requestCount){
            if(NumberUtil.isEven(i)){
                searchCount *= 5;
            }else{
                searchCount *= 2;
            }
            //System.out.println(searchCount);
            i++;
        }
        if(searchCount>max_count){
            searchCount = min_count;
        }
        //System.out.println(searchCount+":end");

        Long size = redisUtil.zCard(near_zset_key);
        if(searchCount>size){
            Integer distance = 10*1000;
            Long cnt = redisUtil.geoSearchStore(near_geo_key, near_zset_key, new Point(lng, lat), new Distance(distance, Metrics.METERS), searchCount);
            //System.out.println(distance);
            while (cnt < requestCount && distance<max_distance){
                distance *= 10;
                cnt = redisUtil.geoSearchStore(near_geo_key, near_zset_key, new Point(lng, lat), new Distance(distance, Metrics.METERS), searchCount);
            }
            //System.out.println(distance+":end");
            redisUtil.expire(near_zset_key, 60*60);
        }
        return redisUtil.zRangeWithScores(near_zset_key, page.getStart(),page.getEnd());
    }

    public Long geoAdd(double lng, double lat, Object obj){
        return redisUtil.geoAdd(near_geo_key, new Point(lng,lat), obj);
    }

    public Long geoRemove(Object obj){
        return redisUtil.geoRemove(near_geo_key, obj);
    }

}

同步mysql表数据

设计思路

  1. 用table_name做key, table主键为value 组成set结果做分页查询.
  2. table_name:主键 为key, 主键对象为value 组成hash做数据查询.
  3. table_name:field_name:field_value 为key, 主键为value 组成set做条件搜索查询

推荐用spring-data-redis实现

//实例对象
@RedisHash("persons")
@Data
public class Person {
    @Id
    private Long id;
    @Indexed
    private String name;
    private String address;
}

//查询服务, spring-data-redis自动扫描并生成实现bean
public interface PersonRepository extends CrudRepository<Person,Long> {
    List<Person> findByName(String name);
}

//操作实例
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private PersonRepository personRepository;

    @RequestMapping("/add")
    @ResponseBody
    public String add(){
        Person p = new Person();
        p.setId(1L);
        p.setName("张三");
        p.setAddress("北京");
        personRepository.save(p);

        p = new Person();
        p.setId(2L);
        p.setName("李四");
        p.setAddress("昆明");
        personRepository.save(p);
        return "ok";
    }

    @RequestMapping("/query")
    @ResponseBody
    public List<Person> query(String name){
        List<Person> list = personRepository.findByName(name);
        return list;
    }
}

观察生成的数据结构

Redission分布式锁的使用

依赖

<dependency>
	<groupId>org.redisson</groupId>
	<artifactId>redisson</artifactId>
	<version>2.7.0</version>
</dependency>

配置

public class RedissonManager {
	private static Config config = new Config();
	//声明redisso对象
	private static Redisson redisson = null;
	//实例化redisson
	static{
		config.useClusterServers()
		// 集群状态扫描间隔时间,单位是毫秒
		.setScanInterval(2000)
		//cluster方式至少6个节点(3主3从,3主做sharding,3从用来保证主宕机后可以高可用)
		.addNodeAddress("redis://127.0.0.1:6379" )
		.addNodeAddress("redis://127.0.0.1:6380")
;
		//得到redisson对象
		redisson = (Redisson) Redisson.create(config);	}		public static Redisson getRedisson(){		return redisson;	}
}

锁的获取和释放

public class DistributedRedisLock {
	//从配置类中获取redisson对象
	private static Redisson redisson = RedissonManager.getRedisson();
	private static final String LOCK_TITLE = "redisLock_";
	//加锁
	public static boolean acquire(String lockName){
		//声明key对象
		String key = LOCK_TITLE + lockName;
		//获取锁对象
		RLock mylock = redisson.getLock(key);
		//加锁,并且设置锁过期时间3秒,防止死锁的产生 uuid+threadId
		mylock.lock(2,3,TimeUtil.SECOND);
		//加锁成功
		return true;
	}
	//锁的释放
	public static void release(String lockName){
		//必须是和加锁时的同一个key
		String key = LOCK_TITLE + lockName;
		//获取所对象
		RLock mylock = redisson.getLock(key);
		//释放锁(解锁)
		mylock.unlock();
	}
}

集成项目完整示例代码: ZNEW-ADMIN

https://gitee.com/hongy123/znew-admin

一个简单通用的springboot+vue3后台管理系统

相关推荐

史上最全的浏览器兼容性问题和解决方案

微信ID:WEB_wysj(点击关注)◎◎◎◎◎◎◎◎◎一┳═┻︻▄(页底留言开放,欢迎来吐槽)●●●...

平面设计基础知识_平面设计基础知识实验收获与总结
平面设计基础知识_平面设计基础知识实验收获与总结

CSS构造颜色,背景与图像1.使用span更好的控制文本中局部区域的文本:文本;2.使用display属性提供区块转变:display:inline(是内联的...

2025-02-21 16:01 yuyutoo

写作排版简单三步就行-工具篇_作文排版模板

和我们工作中日常word排版内部交流不同,这篇教程介绍的写作排版主要是用于“微信公众号、头条号”网络展示。写作展现的是我的思考,排版是让写作在网格上更好地展现。在写作上花费时间是有累积复利优势的,在排...

写一个2048的游戏_2048小游戏功能实现

1.创建HTML文件1.打开一个文本编辑器,例如Notepad++、SublimeText、VisualStudioCode等。2.将以下HTML代码复制并粘贴到文本编辑器中:html...

今天你穿“短袖”了吗?青岛最高23℃!接下来几天气温更刺激……

  最近的天气暖和得让很多小伙伴们喊“热”!!!  昨天的气温到底升得有多高呢?你家有没有榜上有名?...

CSS不规则卡片,纯CSS制作优惠券样式,CSS实现锯齿样式

之前也有写过CSS优惠券样式《CSS3径向渐变实现优惠券波浪造型》,这次再来温习一遍,并且将更为详细的讲解,从布局到具体样式说明,最后定义CSS变量,自定义主题颜色。布局...

柠檬科技肖勃飞:大数据风控助力信用社会建设

...

你的自我界限够强大吗?_你的自我界限够强大吗英文

我的结果:A、该设立新的界限...

行内元素与块级元素,以及区别_行内元素和块级元素有什么区别?

行内元素与块级元素首先,CSS规范规定,每个元素都有display属性,确定该元素的类型,每个元素都有默认的display值,分别为块级(block)、行内(inline)。块级元素:(以下列举比较常...

让“成都速度”跑得潇潇洒洒,地上地下共享轨交繁华
让“成都速度”跑得潇潇洒洒,地上地下共享轨交繁华

去年的两会期间,习近平总书记在参加人大会议四川代表团审议时,对治蜀兴川提出了明确要求,指明了前行方向,并带来了“祝四川人民的生活越来越安逸”的美好祝福。又是一年...

2025-02-21 16:00 yuyutoo

今年国家综合性消防救援队伍计划招录消防员15000名

记者24日从应急管理部获悉,国家综合性消防救援队伍2023年消防员招录工作已正式启动。今年共计划招录消防员15000名,其中高校应届毕业生5000名、退役士兵5000名、社会青年5000名。本次招录的...

一起盘点最新 Chrome v133 的5大主流特性 ?

1.CSS的高级attr()方法CSSattr()函数是CSSLevel5中用于检索DOM元素的属性值并将其用于CSS属性值,类似于var()函数替换自定义属性值的方式。...

竞走团体世锦赛5月太仓举行 世界冠军杨家玉担任形象大使

style="text-align:center;"data-mce-style="text-align:...

学物理能做什么?_学物理能做什么 卢昌海

作者:曹则贤中国科学院物理研究所原标题:《物理学:ASourceofPowerforMan》在2006年中央电视台《对话》栏目的某期节目中,主持人问过我一个的问题:“学物理的人,如果日后不...

你不知道的关于这只眯眼兔的6个小秘密
你不知道的关于这只眯眼兔的6个小秘密

在你们忙着给熊本君做表情包的时候,要知道,最先在网络上引起轰动的可是这只脸上只有两条缝的兔子——兔斯基。今年,它更是迎来了自己的10岁生日。①关于德艺双馨“老艺...

2025-02-21 16:00 yuyutoo

取消回复欢迎 发表评论: