互联网项目-Redis工具类

redis工具类可直接使用,包含redis的增加删除等api操作,包含分布式锁工具类

package com.demo.redis.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RedisTemplate<String, Object> redisObjectTemplate;

    public Boolean hasKey(String key) {
        return this.redisTemplate.hasKey(key);
    }

    public String get(String key) {
        String message;
        if (hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            message = valueOperations.get();
        } else {
            message = null;
        }
        return message;
    }

    public void put(String key, String value) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
        } else {
            this.update(key, value);
        }

    }

    public void put(String key, Object value) {
        if (!hasKey(key)) {
            BoundValueOperations<String, Object> valueOperations = this.redisObjectTemplate.boundValueOps(key);
            valueOperations.set(value);
        } else {
            this.update(key, value);
        }

    }

    public void put(String key, String value, Long expireTime, TimeUnit timeUnit) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
            if (null != timeUnit) {
                valueOperations.expire(expireTime, timeUnit);
            }

        } else {
            this.update(key, value, expireTime, timeUnit);
        }
    }

    public void put(String key, String value, Date date) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
            if(null != date){
                valueOperations.expireAt(date);
            }
        } else {
            this.update(key, value, date);
        }
    }

    public void remove(String key) {
        if (hasKey(key)) {
            this.redisTemplate.delete(key);
        }
    }

    public void update(String key, String value) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
    }

    public void update(String key, Object value ) {
        BoundValueOperations<String, Object> valueOperations = this.redisObjectTemplate.boundValueOps(key);
        valueOperations.set(value);
    }

    public void update(String key, String value, Long expireTime, TimeUnit timeUnit) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
        if (null != timeUnit)
            valueOperations.expire(expireTime, timeUnit);
    }

    public void update(String key, String value, Date date) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
        if (null != date)
            valueOperations.expireAt(date);
    }

    public void incr(String key) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.increment();
    }

    /**
     * 设置分布式锁
     *
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @param timeout    timeout的时间范围内轮询锁, 单位: 秒
     * @return
     */
    public boolean lock(String key, String value, Long expireTime, TimeUnit timeUnit, Long timeout) {
        long beginTime = System.currentTimeMillis();
        if (timeout == 0) {
            timeout = 600L;
        }
        timeout = TimeUnit.SECONDS.toMillis(timeout);
        try {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            while (System.currentTimeMillis() - beginTime < timeout) {
                Boolean aBoolean = valueOperations.setIfAbsent(value, expireTime, timeUnit);
                if (aBoolean != null && aBoolean) {
                    return true;
                }
                Thread.sleep(50, new Random().nextInt(50));
            }
        } catch (Exception e) {
            throw new RuntimeException("locking error", e);
        }
        return false;
    }

    /**
     * @return void
     * @description 频次限制
     * @params [key, ms, limit]
     **/
    public boolean limit(String key, Long ms, Long limit){
        key = "rate.limiting:" + key;
        Long size=redisTemplate.opsForList().size(key);
        if (size < limit) {
            redisTemplate.opsForList().rightPush(key, String.valueOf(System.currentTimeMillis()));
        } else {
            //最早的
            String time = redisObjectTemplate.opsForList().index(key,0).toString();
            Long now = System.currentTimeMillis();
            log.debug("now {} ,time {}",now,time);
            if (now - Long.valueOf(time) < ms) {
                return false;
            } else {
                redisTemplate.opsForList().rightPush(key,String.valueOf(now));
                redisTemplate.opsForList().trim(key,1,limit);
            }
        }
        return true;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值