The INCR key of redis implements simple traffic statistics

Keywords: Programming Redis

The INCR key of redis implements simple traffic statistics

  • redis INCR document

  • thinking

    • For example, use the incr of redis to write a method on the details page to make auto statistics on the visit.
    • Get all the key s of incr and display them in order
      • It should be noted here that keys cannot be used when taking all keys. Because redis is single threaded and traverses kye in a large amount, which may cause redis to block, we use scan
  • Code

    • Deposit

          /**
          *  Redis Incr Self increment
          * @param serviceName
          * @param id
          */
          public void redisCount(String serviceName,String id){
              boolean flag = redisTemplate.hasKey(serviceName +":"+ id);
              //non-existent
              if (!flag){
                  GenericToStringSerializer genericToStringSerializer = new GenericToStringSerializer(Object.class);
                  redisTemplate.setValueSerializer(genericToStringSerializer);
                  redisTemplate.opsForValue().set(serviceName +":"+ id, 1);
              } else {
                  redisTemplate.opsForValue().increment(serviceName +":"+ id);
              }
      
          }
      

    The setValueSerializer here, because the value initialization sequence is String, needs to be serialized to store the value type

    • take
    	/**
    	 * Get all keys through the scan of redis
    	 * @param key
    	 * @return
    	 */
    	public void scan(String pattern, Consumer<byte[]> consumer) {
    		this.stringRedisTemplate.execute((RedisConnection connection) -> {
    			try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) {
    				cursor.forEachRemaining(consumer);
    				return null;
    			} catch (IOException e) {
    				e.printStackTrace();
    				throw new RuntimeException(e);
    			}
    		});
    	}
    
    
    	/**
    	 * Get qualified key
    	 * @param pattern	expression
    	 * @return
    	 */
    	public List<String> keys(String pattern) {
    		List<String> keys = new ArrayList<>();
    		this.scan(pattern, item -> {
    			//Qualified key
    			String key = new String(item, StandardCharsets.UTF_8);
    			keys.add(key);
    		});
    		return keys;
    	}
    

    For the method and introduction of scan access, here you can refer to the information on the Internet. Data address

Posted by jeffshead on Wed, 22 Apr 2020 07:24:22 -0700