當(dāng)前位置:首頁(yè) > IT技術(shù) > 其他 > 正文

用戶凍結(jié)解凍邏輯與代碼
2022-04-25 22:56:20

1.凍結(jié)用戶,將數(shù)據(jù)存入Redis,并設(shè)置key的失效時(shí)間。
2.解凍用戶,刪除Redis數(shù)據(jù)
3.探花系統(tǒng)在用戶登錄,評(píng)論,發(fā)布動(dòng)態(tài)時(shí)判斷其凍結(jié)狀態(tài),如果被凍結(jié)拋出異常

用戶狀態(tài)枚舉

public enum UserStatusEnum {

    FREEZE_LOGIN("1","凍結(jié)登錄"),
    FREEZE_FANYAN("2","凍結(jié)評(píng)論"),
    FREEZE_DONGTAI("3","凍結(jié)發(fā)布動(dòng)態(tài)");

    private String code;
    private String msg;

    UserStatusEnum(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

后臺(tái)代碼

   /**
     * 凍結(jié)用戶
     * @param map
     * @return
     */
    public HashMap<String, String> freezeUser(Map map) {
//        1.構(gòu)造key
        String userId = map.get("userId").toString();
        String key = Constants.FREEZE_USER + userId;
//        2.獲取凍結(jié)時(shí)間,設(shè)置redis的存活時(shí)間
        int day=0;
        Integer freezingTime = Integer.parseInt(map.get("freezingTime").toString()) ;
        if (freezingTime==1){
            day=3;
        }
        if (freezingTime==2){
            day=7;
        }
//        3.存入redis
        String value = JSON.toJSONString(map);
        if (day>0){
            redisTemplate.opsForValue().set(key,value,day,TimeUnit.DAYS);
        }else {
            redisTemplate.opsForValue().set(key,value);
        }
        HashMap<String, String> msg = new HashMap<>();
        msg.put("message","凍結(jié)用戶成功");
        return msg;
    }

    /**
     * 解凍用戶
     * @param map
     * @return
     */
    public HashMap<Object, Object> unfreezeUser(Map map) {
        String userId = map.get("userId").toString();
        String key = Constants.FREEZE_USER + userId;
        redisTemplate.delete(key);

        HashMap<Object, Object> res = new HashMap<>();
        res.put("message","解凍用戶成功");
        return res;
    }

  前臺(tái)代碼

@Service
public class UserFreezeService {

    @Autowired
    private RedisTemplate redisTemplate;

    public void checkStatus(String freezeRange, Long userId) {
//            取出value,判斷封禁類型
        String key = Constants.FREEZE_USER + userId.toString();
        String vlaue = (String) redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(vlaue)) {
            Map map = JSON.parseObject(vlaue, Map.class);
            String range = (String) map.get("freezingRange");
//            取出封禁類型進(jìn)行判斷
            if (freezeRange.equals(range)) {
                throw new BusinessException(ErrorResult.countError());
            }
        }
    }
}

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >