Realize distributed auto-increment primary key based on Redis


1. Principle

The core principle of implementing distributed auto-incrementing primary keys based on Redis is INCRthe command. Each call adds 1 to the digital value stored in the corresponding key, so it can easily implement auto-incrementing primary keys similar to Mysql databases.

Disadvantages : Only numeric primary keys are supported. If the cache is lost, the primary key will be duplicated.

[root@Mobile redis-stable]# redis-cli 
127.0.0.1:6379> incr mycounter
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> incr mycounter
(integer) 1
127.0.0.1:6379> incr mycounter
(integer) 2
127.0.0.1:6379>

Two, actual combat

The overall project still adoptsspring boot + mybaits-plus + mysql

For other content, please refer to: Mybatis-plus Snowflake Algorithm Generates Id Using Detailed Explanation

This article mainly replaces the default ID generator of the snowflake algorithm with a custom Redis distributed ID generator.

1. New redis dependency in maven

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
   </dependency>

2. Redis connection attribute configuration

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456

3. Customize Redis primary key generator RedisIdentifierGenerator

@Component
public class RedisIdentifierGenerator implements IdentifierGenerator{
    
    
    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Number nextId(Object entity) {
    
    
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
        String bizKey = entity.getClass().getName();
        //根据bizKey调用分布式ID生成
        return redisTemplate.opsForValue().increment(bizKey);
    }
}

4. Specify the generation strategy of the primary key idIdType.ASSIGN_ID

@TableName(value ="user")
@Data
@EqualsAndHashCode
public class User implements Serializable {
    
    
    /**
     * 主键ID
     */
   @TableId(value = "id",type = IdType.ASSIGN_ID)
    //@TableId(value = "id",type = IdType.AUTO)
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 邮箱
     */
    private String email;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
}

5. Test

    @Test
    public void testInsert() {
    
    
        System.out.println("----- insert method test ------");
        User user = new User();
        user.setName("test");
        user.setAge(13);
        user.setEmail("[email protected]");
        userMapper.insert(user);
        System.out.println(user.toString());
    }

The primary key id is 1 assigned by RedisIdentifierGenerator
insert image description here

Guess you like

Origin blog.csdn.net/w1014074794/article/details/129404281