springboot+redis 는 좋아요,탐색,소장,댓 글 등 수량의 증감 작업 을 실현 합 니 다.

springboot+redis 는 좋아요,탐색,소장,댓 글 등 수량의 증감 작업 을 실현 합 니 다.
머리말
처음으로 블 로 그 를 쓰 고 기록 해 보 세 요.
在这里插入图片描述
최근 한 게시 물의 수집,좋아요 수 를 누 르 는 기능 을 했 습 니 다.사실 이전에 도 비슷 한 기능 을 한 적 이 있 습 니 다.예전 에 사용 해 온 my sql 은 항상 이런 빈번 한 변화 가 필요 한 값 에 대해 Mysql 에 너무 큰 스트레스 를 주어 서 는 안 된다 고 느 꼈 기 때 문 입 니 다.이 글 은 redis 를 사용 하여 오래 지속 되 었 습 니 다.다음은 핵심 코드 를 붙 입 니 다.DataResponse 는 프로젝트 에서 사용 한 결과 패키지 실체 클래스 입 니 다.forumDTO 는 이 기능 의 매개 변수 실체 입 니 다.필요 하 시 면 메 시 지 를 남 겨 주세요.
상수:

 private static final String DEFAULT_VALUE = "0:0:0:0:0:0";
  public static final Byte BYTE_ZERO = 0;
  public static final Byte BYTE_ONE = 1;
  public static final Byte BYTE_TWO = 2;
  public static final Byte BYTE_THREE = 3;
  public static final Byte BYTE_FOUR = 4;
  public static final Byte BYTE_FIVE = 5;
  public static final Byte BYTE_SIX = 6;

 @Override
  public DataResponse keepNum(ForumDTO forumDTO) {
    //   id     key
    String key = forumDTO.getPostId().toString();
    //get   id
    String userId = forumDTO.getUserId();
    String count, newCount;
    //     key
    BoundHashOperations<String, Object, Object> post = redisTemplate.boundHashOps("post:");
    //  hKey
    // count: 0  -    1    2    3   4  -   
    if (null == post.get(key)) {
      //  set
      post.put(key, DEFAULT_VALUE);
      //        count
      count = post.get(key).toString();
    } else {
      //      count
      count = post.get(key).toString();
    }
    // operationType 1    2      3    4  -  
    String prefix;
    switch (forumDTO.getOperationType()) {
      case 1:
        //       OPERATIONTYPE 1 :       
        newCount = resetValue(count, BYTE_THREE, true);
        post.put(key, newCount);
        break;
      case 2:
        //    -  
        prefix = "thumbs:post";
        switch (forumDTO.getClickType()) {
          case 0:
            /**
             * OPERATIONTYPE 2: + CLICKTYPE 0 =      
             * 0  
             *  redis        d   :177488r88t78r78r7
             * count: 0  -    1    2    3   4  -   
             *           redis      redis value        
             *     +1    
             */
            if (redisTemplate.opsForSet().isMember(prefix + ":" + key, prefix + ":" + userId)) {
              return DataResponse.fail("       ");
            } else {
              redisTemplate.opsForSet().add(prefix + ":" + key, prefix + ":" + userId);
            }
            newCount = resetValue(count, BYTE_ZERO, true);
            //set to redis
            post.put(key, newCount);
            break;
          case 1:
            //OPERATIONTYPE 2: + CLICKTYPE 1 =       
            //1      
            if (!redisTemplate.opsForSet().isMember(prefix + ":" + key, prefix + ":" + userId)) {
              //    
              return DataResponse.fail("       ");
            } else {
              //  
              redisTemplate.opsForSet().remove(prefix + ":" + key, prefix + ":" + userId);
            }
            newCount = resetValue(count, BYTE_ZERO, false);
            post.put(key, newCount);
            break;
        }
        break;
      case 3:
        prefix = "collection:post";
        List<MqMessage> sendList = new LinkedList<>();
        MqMessage mqMessage = new MqMessage();
        switch (forumDTO.getClickType()) {
          //OPERATIONTYPE 3 + CLICKTYPE 0 =     
          case 0:
            //  +1
            //    id +   id   redis   
            if (redisTemplate.opsForSet().isMember(prefix + ":" + key, prefix + ":" + userId)) {
              //    
              return DataResponse.fail("       ");
            }
            //add
            redisTemplate.opsForSet().add(prefix + ":" + key, prefix + ":" + userId);
            //set to redis
            newCount = resetValue(count, BYTE_TWO, true);
            post.put(key, newCount);
            mqMessage.setType(new Byte("9"));
            mqMessage.setSenderId(userId);
            mqMessage.setPostId(forumDTO.getPostId());
            sendList.add(mqMessage);
            this.sendMq.send(sendList);
            break;
          //OPERATIONTYPE 3 + CLICKTYPE 1 =     
          case 1:
            //    
            //   redis            
            if (!redisTemplate.opsForSet().isMember(prefix + ":" + key, prefix + ":" + userId)) {
              //    
              return DataResponse.fail("       ");
            }
            //  
            redisTemplate.opsForSet().remove(prefix + ":" + key, prefix + ":" + userId);
            newCount = resetValue(count, BYTE_TWO, false);
            post.put(key, newCount);
            mqMessage.setType(new Byte("10"));
            mqMessage.setSenderId(userId);
            mqMessage.setPostId(forumDTO.getPostId());
            sendList.add(mqMessage);
            this.sendMq.send(sendList);
            break;
        }
        break;
      case 4:
        //    -  
        // OPERATIONTYPE 4: + CLICKTYPE 0 =      
        if (null == forumDTO.getCommentId()) {
          return DataResponse.fail("  id    ");
        }
        String commentNum, ckey = forumDTO.getCommentId().toString();
        BoundHashOperations<String, Object, Object> comment = redisTemplate.boundHashOps("post:comment");
        if (null == comment.get(ckey)) {
          //  set
          comment.put(ckey, "0");
          //        count
          commentNum = comment.get(ckey).toString();
        } else {
          //      count
          commentNum = comment.get(ckey).toString();
        }
        //   
        prefix = "thumbs:comment";
        switch (forumDTO.getClickType()) {
          case 0:
            /**
             * 0  
             *  redis        d   :177488r88t78r78r7
             * count: 0  -    1    2    3   4  -   
             *           redis      redis value        
             *     +    
             */
            if (redisTemplate.opsForSet().isMember(prefix + ":" + ckey, prefix + ":" + userId)) {
              return DataResponse.fail("       ");
            } else {
              redisTemplate.opsForSet().add(prefix + ":" + ckey, prefix + ":" + userId);
            }
            //set to redis
            comment.put(ckey, cResetValue(commentNum, true));
            break;
          case 1:
            //1      
            if (!redisTemplate.opsForSet().isMember(prefix + ":" + ckey, prefix + ":" + userId)) {
              //    
              return DataResponse.fail("       ");
            } else {
              //  
              redisTemplate.opsForSet().remove(prefix + ":" + ckey, prefix + ":" + userId);
            }
            newCount = cResetValue(commentNum, false);
            comment.put(ckey, newCount);
            break;
        }
        break;
      default:
        DataResponse.fail(ResponseEnum.FAILED);
    }
    return DataResponse.success(ResponseEnum.SUCCESS);
  }
 
resetValue 코드:

 /**
   *     : <br>
   * 〈   、        〉
   * @param val    
   * @param type  0      1    2    3   4     
   * @param isPlus        true +  false -
   * @Return: java.lang.String
   * @Author:  
   * @Date: 2020/8/5 10:27
   * StringUtils :import org.apache.commons.lang3.StringUtils;
   *     jdk    split  ; jdk        ,    。
   */
  private String resetValue(String val, int j, boolean isPlus) {
    String[] value = StringUtils.split(val, ":");
    Long temp = Long.valueOf(value[j]);
    StringBuffer sb = new StringBuffer(16);
    if (isPlus) {
      temp += 1;
    } else {
      temp -= 1;
    }
    value[j] = temp.toString();
    for (int i = 0, len = value.length; i < len; i++) {
      if (i != len - 1) {
        sb.append(value[i]).append(":");
      }else {
        sb.append(value[i]);
      }
    }
    return sb.toString();
  }
총결산
여기 서 spring boot+redis 가 좋아요,조회,소장,댓 글 등 수량 증감 작업 을 실현 하 는 것 에 관 한 글 을 소개 합 니 다.더 많은 관련 spring boot+redis 가 좋아요 수집 댓 글 내용 을 실현 하 는 것 은 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기