Redis生成分布式系统全局唯一ID的实现

 更新时间:2021年10月25日 10:17:19   作者:李白与酒  
在互联网系统中,并发越大的系统,数据就越大,数据越大就越需要分布式,本文主要介绍了Redis生成分布式系统全局唯一ID的实现,感兴趣的可以了解一下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

分布式系统全局唯一ID

在互联网系统中,并发越大的系统,数据就越大,数据越大就越需要分布式,而大量的分布式数据就越需要唯一标识来识别它们。

例如淘宝的商品系统有千亿级别商品,订单系统有万亿级别的订单数据,这些数据都是日渐增长,传统的单库单表是无法支撑这种级别的数据,必须对其进行分库分表;一旦分库分表,表的自增ID就失去了意义;故需要一个全局唯一的ID来标识每一条数据(商品、订单)。

e.g: 一张表1亿条数据,被分库分表10张表,原先的ID就失去意义,所以需要全局唯一ID来标识10张表的数据。

全局唯一的ID生成的技术方案有很多,业界比较有名的有 UUID、Redis、Twitter的snowflake算法、美团Leaf算法。

基于Redis INCR 命令生成分布式全局唯一ID

INCR 命令主要有以下2个特征:

  • Redis的INCR命令具备了“INCR AND GET”的原子操作
  • Redis是单进程单线程架构,INCR命令不会出现ID重复

基于以上2个特性,可以采用INCR命令来实现分布式全局ID生成。

采用Redis生成商品全局唯一ID

Project Directory

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.8.RELEASE</version>
        <relativePath/>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.fool.redis</groupId>
    <artifactId>redis-string-id</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

spring.application.name=redis-spring-id
server.port=8888

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=
spring.redis.timeout=2000
spring.redis.pool.max-active=10
spring.redis.pool.max-wait=1000
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.pool.num-tests-per-eviction-run=1024
spring.redis.pool.time-between-eviction-runs-millis=30000
spring.redis.pool.min-evictable-idle-time-millis=60000
spring.redis.pool.soft-min-evictable-idle-time-millis=10000
spring.redis.pool.test-on-borrow=true
spring.redis.pool.test-while-idle=true
spring.redis.pool.block-when-exhausted=false

SRC

Application.java

package org.fool.redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Product.java

package org.fool.redis.model;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Product {
    private Long id;
    private String name;
    private BigDecimal price;
    private String detail;
}

IdGeneratorService.java

package org.fool.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class IdGeneratorService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String ID_KEY = "id:generator:product";

    public Long incrementId() {
        return stringRedisTemplate.opsForValue().increment(ID_KEY);
    }
}

ProductController.java

package org.fool.redis.controller;

import lombok.extern.slf4j.Slf4j;
import org.fool.redis.model.Product;
import org.fool.redis.service.IdGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping(value = "/product")
public class ProductController {
    @Autowired
    private IdGeneratorService idGeneratorService;

    @PostMapping(value = "/create")
    public String create(@RequestBody Product obj) {
        //生成分布式id
        long id = idGeneratorService.incrementId();

        //使用全局id 代替数据库的自增id
        obj.setId(id);

        //取模(e.g: 这里分为8张表,海量数据可以分为1024张表),计算表名
        int table = (int) id % 8;
        String tableName = "product_" + table;

        log.info("insert to table: {}, with content: {}", tableName, obj);

        return "insert to table: " + tableName + " with content: " + obj;
    }
}

Test

curl --location --request POST 'http://localhost:8888/product/create' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "Car",
    "price": "300000.00",
    "detail": "Lexus Style"
}'

Console Output

到此这篇关于Redis生成分布式系统全局唯一ID的实现的文章就介绍到这了,更多相关Redis生成分布式系统全局唯一ID内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!

相关文章

  • Redisson 加锁解锁的实现

    Redisson 加锁解锁的实现

    本文主要介绍了Redisson 加锁解锁的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer区别

    Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializ

    本文主要介绍了Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • CentOS系统安装Redis及Redis的PHP扩展详解

    CentOS系统安装Redis及Redis的PHP扩展详解

    这篇文章主要介绍了CentOS系统下安装Redis数据的教程,以及详解了Redis数据库的PHP扩展,文中介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • Redis Cluster集群收缩主从节点详细教程

    Redis Cluster集群收缩主从节点详细教程

    集群收缩的源端就是要下线的主节点,目标端就是在线的主节点,这篇文章主要介绍了Redis Cluster集群收缩主从节点详细教程,需要的朋友可以参考下
    2021-11-11
  • Redis Desktop Manager(Redis可视化工具)安装及使用图文教程

    Redis Desktop Manager(Redis可视化工具)安装及使用图文教程

    这篇文章主要介绍了Redis Desktop Manager(Redis可视化工具)安装及使用图文教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • redis+lua实现限流的项目实践

    redis+lua实现限流的项目实践

    redis有很多限流的算法(比如:令牌桶,计数器,时间窗口)等,在分布式里面进行限流的话,我们则可以使用redis+lua脚本进行限流,下面就来介绍一下redis+lua实现限流
    2023-10-10
  • 关于Redis持久化的深入探究

    关于Redis持久化的深入探究

    Redis持久化是将内存中的数据保存到磁盘,以防止数据丢失。Redis提供了两种持久化方式:RDB和AOF,本文将给大家详解介绍Redis持久化,感兴趣的同学可以跟着小编一起来学习
    2023-05-05
  • redis中热key问题该如何解决

    redis中热key问题该如何解决

    这篇文章主要给大家介绍了关于redis中热key问题该如何解决的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用redis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-05-05
  • Redis中LRU淘汰策略的深入分析

    Redis中LRU淘汰策略的深入分析

    这篇文章主要给大家介绍了关于Redis中LRU淘汰策略的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Redis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • 深入解析Redis的LRU与LFU算法实现

    深入解析Redis的LRU与LFU算法实现

    这篇文章主要重点介绍了Redis的LRU与LFU算法实现,并分析总结了两种算法的实现效果以及存在的问题,并阐述其优劣特性,感兴趣的小伙伴跟着小编一起来看看吧
    2023-07-07

最新评论

?


http://www.vxiaotou.com