Distributed globally unique ID (two)

Redis implements a distributed unique ID. In fact, this is also very simple. It mainly uses the increment method of the redis String data structure.

principle:

Using the increment method, adding 1 each time, mainly using the high performance and single thread of redis.

Method to realize:

The core code is as follows, if it is to ensure the same length, in fact, the value can be initialized in advance. The current one is gradually increasing from 1, 2.....


	/**
	 * 注入Redis字符串模板
	 */
	@Autowired
	private StringRedisTemplate redisTemplate;

       /**
	 * 当前的值 + 1
	 *
	 * @param key 键
	 * @return 返回操作之后的值
	 */
	public Long increment(final String key) {
		return this.redisTemplate.opsForValue().increment(key, 1);
	}

	/**
	 * 当前的值加 + value
	 *
	 * @param key   键
	 * @param value 值
	 * @return 返回操作之后的值
	 */
	public Long incrementBy(final String key, final long value) {
		return this.redisTemplate.opsForValue().increment(key, value);
	}

 

Guess you like

Origin blog.csdn.net/qq_38428623/article/details/105495779