AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

基于 DDD 的互聯網“贊&踩”系統

來源: 責編: 時間:2023-10-30 09:07:06 245觀看
導讀該文是系統的用戶手冊,主要體現系統功能和所支持的高級特性,關于系統的核心設計正在整理中,請稍安勿躁1. 背景隨著社交媒體的普及,用戶生成的內容數量急劇增加。為了幫助用戶更好地發現和分享內容,許多社交媒體平臺都提供

該文是系統的用戶手冊,主要體現系統功能和所支持的高級特性,關于系統的核心設計正在整理中,請稍安勿躁JVU28資訊網——每日最新資訊28at.com

1. 背景

隨著社交媒體的普及,用戶生成的內容數量急劇增加。為了幫助用戶更好地發現和分享內容,許多社交媒體平臺都提供了贊/踩服務。JVU28資訊網——每日最新資訊28at.com

2. 目標

贊/踩服務是一種用戶反饋機制。隨著社交媒體的普及和發展,人們越來越喜歡在一種平臺上分享自己的觀點和生活,這時就需要一種形式化的反饋機制來快速評價這些信息的好壞。贊/踩服務的目標是為了提高用戶互動性,增加內容的社會影響力,從而增加活躍用戶數量。JVU28資訊網——每日最新資訊28at.com

3. 快速入門

系統所涉及的功能包括:JVU28資訊網——每日最新資訊28at.com

功能JVU28資訊網——每日最新資訊28at.com

描述JVU28資訊網——每日最新資訊28at.com

贊/踩JVU28資訊網——每日最新資訊28at.com

用戶可以點擊對應的贊或踩按鈕,以表達自己的喜好或不喜好JVU28資訊網——每日最新資訊28at.com

取消贊/踩JVU28資訊網——每日最新資訊28at.com

用戶可以取消之前的贊/踩,以更正自己的想法JVU28資訊網——每日最新資訊28at.com

計數器JVU28資訊網——每日最新資訊28at.com

贊和踩的數量都需要計數器,用于顯示文章或評論的受歡迎程度和社交影響力等JVU28資訊網——每日最新資訊28at.com

贊/踩歷史JVU28資訊網——每日最新資訊28at.com

用戶可以查看自己贊/踩的歷史記錄,以查看自己對文章或評論的態度JVU28資訊網——每日最新資訊28at.com

3.1. 開發環境

基于 Spring Boot 框架進行開發,以 DDD 作為業務邏輯承載模型。JVU28資訊網——每日最新資訊28at.com

框架JVU28資訊網——每日最新資訊28at.com

版本JVU28資訊網——每日最新資訊28at.com

依賴說明JVU28資訊網——每日最新資訊28at.com

JDKJVU28資訊網——每日最新資訊28at.com

1.8+JVU28資訊網——每日最新資訊28at.com

運行環境JVU28資訊網——每日最新資訊28at.com

Spring BootJVU28資訊網——每日最新資訊28at.com

2.3.12.RELEASEJVU28資訊網——每日最新資訊28at.com


JVU28資訊網——每日最新資訊28at.com

Spring DataJVU28資訊網——每日最新資訊28at.com

2.3.9.RELEASEJVU28資訊網——每日最新資訊28at.com

基于 JPA 實現持久化;基于 Redis 完成緩存加速(可選)JVU28資訊網——每日最新資訊28at.com

LegoJVU28資訊網——每日最新資訊28at.com

0.1.22JVU28資訊網——每日最新資訊28at.com

DDD 模型落地JVU28資訊網——每日最新資訊28at.com

springfoxJVU28資訊網——每日最新資訊28at.com

3.0.0JVU28資訊網——每日最新資訊28at.com

文檔管理JVU28資訊網——每日最新資訊28at.com

RocketMQJVU28資訊網——每日最新資訊28at.com

2.2.1JVU28資訊網——每日最新資訊28at.com

領域事件,異步處理(可選)JVU28資訊網——每日最新資訊28at.com

Sharding SphereJVU28資訊網——每日最新資訊28at.com

4.4.1JVU28資訊網——每日最新資訊28at.com

分庫分表(可選)JVU28資訊網——每日最新資訊28at.com

3.2. 模塊介紹

該項目使用標準的 “六邊形架構”,對業務和技術進行分離,所以模塊較多,但層次更為清晰。JVU28資訊網——每日最新資訊28at.com

模塊JVU28資訊網——每日最新資訊28at.com

作用JVU28資訊網——每日最新資訊28at.com

domainJVU28資訊網——每日最新資訊28at.com

核心邏輯層,DDD 中核心組件,包括實體、值對象、聚合根、領域服務等JVU28資訊網——每日最新資訊28at.com

appJVU28資訊網——每日最新資訊28at.com

應用服務層,DDD 中的應用服務,主要負責流程編排JVU28資訊網——每日最新資訊28at.com

infrastructureJVU28資訊網——每日最新資訊28at.com

基礎設施層,主要負責與 DB 或其他服務進行通訊JVU28資訊網——每日最新資訊28at.com

apiJVU28資訊網——每日最新資訊28at.com

RPC 服務中的接口定義,被 FeignClient 和 FeignService 依賴JVU28資訊網——每日最新資訊28at.com

FeignServiceJVU28資訊網——每日最新資訊28at.com

api 中接口的實際實現者,完成接口的適配JVU28資訊網——每日最新資訊28at.com

FeignClientJVU28資訊網——每日最新資訊28at.com

api 中Proxy實現者,方便使用方直接調用JVU28資訊網——每日最新資訊28at.com

bootstrapJVU28資訊網——每日最新資訊28at.com

應用啟動入口,包括 Spring Boot 入口和所有配置JVU28資訊網——每日最新資訊28at.com

3.3. 啟動項目

3.3.1. 建庫建表

建表語句在infrastructure/src/main/resources/sql 目標下,包括單庫和分庫分表配置。單庫建表語句如下:JVU28資訊網——每日最新資訊28at.com

create table dislike_action(    id          bigint auto_increment primary key,    create_time datetime    not null,    delete_time datetime    null,    update_time datetime    null,    vsn         int         not null,    status      char(16)    not null,    target_id   bigint      not null,    target_type varchar(16) not null,    user_id     bigint      not null,    constraint unq_user_target        unique (user_id, target_type, target_id));create table dislike_target_count(    id          bigint auto_increment primary key,    create_time datetime    not null,    delete_time datetime    null,    update_time datetime    null,    vsn         int         not null,    count       bigint      not null,    target_id   bigint      not null,    target_type varchar(16) not null,    constraint unq_target        unique (target_id, target_type));create table like_action(    id          bigint auto_increment primary key,    create_time datetime    not null,    delete_time datetime    null,    update_time datetime    null,    vsn         int         not null,    status      char(16)    not null,    target_id   bigint      not null,    target_type varchar(16) not null,    user_id     bigint      not null,    constraint unq_user_target        unique (user_id, target_type, target_id));create table like_target_count(    id          bigint auto_increment primary key,    create_time datetime    not null,    delete_time datetime    null,    update_time datetime    null,    vsn         int         not null,    count       bigint      not null,    target_id   bigint      not null,    target_type varchar(16) not null,    constraint unq_target        unique (target_id, target_type));

3.3.2. 修改數據庫配置

修改bootstrap/src/main/resource/application.yml 增加數據配置,具體如下:JVU28資訊網——每日最新資訊28at.com

spring:  datasource:    driver-class-name: com.mysql.cj.jdbc.Driver    url: jdbc:mysql://127.0.0.1:3306/like    username: root    password: root

3.3.3. 啟動應用程序

直接運行 bootstrap 模塊下的 LikeApplication 類,輸入地址:http://127.0.0.1:8080/swagger-ui/JVU28資訊網——每日最新資訊28at.com

當看到如下界面證明程序啟動成功:JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

3.3. 核心 API

核心接口如下:JVU28資訊網——每日最新資訊28at.com

功能JVU28資訊網——每日最新資訊28at.com

請求地址JVU28資訊網——每日最新資訊28at.com

參數類型JVU28資訊網——每日最新資訊28at.com

參數說明JVU28資訊網——每日最新資訊28at.com

返回結果JVU28資訊網——每日最新資訊28at.com

cur DemoJVU28資訊網——每日最新資訊28at.com

點贊JVU28資訊網——每日最新資訊28at.com

POST /feignService/action/command/likeJVU28資訊網——每日最新資訊28at.com

RequestBodyJVU28資訊網——每日最新資訊28at.com

{"userId": 用戶id, "targetType": 目標對象類型,"targetId": 目標對象 id}JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

curl -X POST "http://127.0.0.1:8080/feignService/action/command/like" -H "accept: /" -H "Content-Type: application/json" -d "{"targetId":1,"targetType":"TEST","userId":2}"JVU28資訊網——每日最新資訊28at.com

取消點贊JVU28資訊網——每日最新資訊28at.com

POST /feignService/action/command/unlikeJVU28資訊網——每日最新資訊28at.com

RequestBodyJVU28資訊網——每日最新資訊28at.com

{"userId": 用戶id, "targetType": 目標對象類型,"targetId": 目標對象 id}JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

curl -X POST "http://127.0.0.1:8080/feignService/action/command/unlike" -H "accept: /" -H "Content-Type: application/json" -d "{"targetId":1,"targetType":"test","userId":2}"JVU28資訊網——每日最新資訊28at.com

獲取點贊數量JVU28資訊網——每日最新資訊28at.com

GET /feignService/targetCount/query/getLikeCountByTargetJVU28資訊網——每日最新資訊28at.com

RequestParamJVU28資訊網——每日最新資訊28at.com

type:目標類型;ids:目標id集合JVU28資訊網——每日最新資訊28at.com

[{"targetType":目標對象類型,“targetId":目標對象id,"count":點贊數量}]JVU28資訊網——每日最新資訊28at.com

curl -X GET "http://127.0.0.1:8080/feignService/targetCount/query/getLikeCountByTarget?type=test&ids=1" -H "accept: /"JVU28資訊網——每日最新資訊28at.com

獲取點贊記錄JVU28資訊網——每日最新資訊28at.com

GET /feignService/action/query/getLikeByUserAndTypeJVU28資訊網——每日最新資訊28at.com

RequestParamJVU28資訊網——每日最新資訊28at.com

type:目標類型;userId:userIdJVU28資訊網——每日最新資訊28at.com

[{"targetType":目標對象類型,“targetId":目標對象id,"userId":用戶id,"valid":是否有效}]JVU28資訊網——每日最新資訊28at.com

curl -X GET "http://127.0.0.1:8080/feignService/action/query/getLikeByUserAndType?userId=2&type=test" -H "accept: /"JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

POST /feignService/action/command/dislikeJVU28資訊網——每日最新資訊28at.com

RequestBodyJVU28資訊網——每日最新資訊28at.com

{"userId": 用戶id, "targetType": 目標對象類型,"targetId": 目標對象 id}JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

curl -X POST "http://127.0.0.1:8080/feignService/action/command/dislike" -H "accept: /" -H "Content-Type: application/json" -d "{"targetId":1,"targetType":"test","userId":2}"JVU28資訊網——每日最新資訊28at.com

取消踩JVU28資訊網——每日最新資訊28at.com

POST /feignService/action/command/unDislikeJVU28資訊網——每日最新資訊28at.com

RequestBodyJVU28資訊網——每日最新資訊28at.com

{"userId": 用戶id, "targetType": 目標對象類型,"targetId": 目標對象 id}JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

curl -X POST "http://127.0.0.1:8080/feignService/action/command/unDislike" -H "accept: /" -H "Content-Type: application/json" -d "{"targetId":1,"targetType":"test","userId":2}"JVU28資訊網——每日最新資訊28at.com

獲取踩數量JVU28資訊網——每日最新資訊28at.com

GET /feignService/targetCount/query/getDislikeCountByTypeJVU28資訊網——每日最新資訊28at.com

RequestParamJVU28資訊網——每日最新資訊28at.com

type:目標類型;ids:目標id集合JVU28資訊網——每日最新資訊28at.com

[{"targetType":目標對象類型,“targetId":目標對象id,"count":點贊數量}]JVU28資訊網——每日最新資訊28at.com

curl -X GET "http://127.0.0.1:8080/feignService/targetCount/query/getDislikeCountByType?type=test&ids=1" -H "accept: /"JVU28資訊網——每日最新資訊28at.com

獲取點贊記錄JVU28資訊網——每日最新資訊28at.com

GET /feignService/action/query/getDislikeByUserAndTypeJVU28資訊網——每日最新資訊28at.com

RequestParamJVU28資訊網——每日最新資訊28at.com

type:目標類型;userId:userIdJVU28資訊網——每日最新資訊28at.com

[{"targetType":目標對象類型,“targetId":目標對象id,"userId":用戶id,"valid":是否有效}]JVU28資訊網——每日最新資訊28at.com

curl -X GET "http://127.0.0.1:8080/feignService/action/query/getDislikeByUserAndType?userId=2&type=test" -H "accept: /"JVU28資訊網——每日最新資訊28at.com

核心API直接在 Swagger UI 上進行測試即可!!!JVU28資訊網——每日最新資訊28at.com

4. 高級特性

4.1. 自定義業務驗證

流程中涉及兩個重要的概念:JVU28資訊網——每日最新資訊28at.com

  • ActionUser: 操作 贊或踩 的用戶;
  • ActionTarget: 贊或踩 的目的對象;

在實際業務場景,需要對這兩個對象的有效性進行驗證,比如:JVU28資訊網——每日最新資訊28at.com

  • ActionUser

用戶是否存在?JVU28資訊網——每日最新資訊28at.com

用戶狀態是否有效?JVU28資訊網——每日最新資訊28at.com

是否是黑名單用戶?JVU28資訊網——每日最新資訊28at.com

  • ActionTarget
  • 目標對象是否存在?
  • 目標對象是否已經下線/禁用?

這些功能擴展直接實現對應的 Loader 即可。JVU28資訊網——每日最新資訊28at.com

4.1.1. ActionUser 擴展

ActionUser 定義如下:JVU28資訊網——每日最新資訊28at.com

public class ActionUser {    @Column(name = "user_id", updatable = false)    private Long userId;    @Transient    private boolean valid;}

如果用戶狀態存在問題,直接將 valid 置為 false 即可。JVU28資訊網——每日最新資訊28at.com

ActionUserLoader 定義如下:JVU28資訊網——每日最新資訊28at.com

public interface ActionUserLoader {    ActionUser loadByUserId(Long userId);}

只需實現 ActionUserLoader 并注冊為 Spring 托管 Bean 即可,具體如下:JVU28資訊網——每日最新資訊28at.com

@Component(value = LoadActionUserByUserId.BEAN_NAME)public class TestActionUserLoader implements ActionUserLoader {    @Override    public ActionUser loadByUserId(Long userId) {        if (userId == null || userId.longValue() < 0){            return ActionUser.apply(userId, false);        }else {            return ActionUser.apply(userId);        }    }}

當 userId 為 null 或者 小于 0 時,表明為無效用戶,將 valid 設置為 false。JVU28資訊網——每日最新資訊28at.com

【備注】Bean 必須注冊為LoadActionUserByUserId.BEAN_NAME(actionUserLoader),否則框架將無法識別。JVU28資訊網——每日最新資訊28at.com

4.1.2. ActionTarget 擴展

ActionTarget 定義如下:JVU28資訊網——每日最新資訊28at.com

public class ActionTarget {    @Column(name = "target_type", updatable = false)    private String type;    @Column(name = "target_id", updatable = false)    private Long id;    @Transient    private boolean valid;}

如果目標對象狀態存在問題,直接將 valid 置為 false 即可。JVU28資訊網——每日最新資訊28at.com

由于系統中可以存在多種目標對象,為每個類型提供單獨的 Loader,接口如下:JVU28資訊網——每日最新資訊28at.com

public interface SingleActionTargetLoader {    /**     * 是否支持 type 類型的 Target     * @param type     * @return     */    boolean support(String type);    /**     * 加載 Target 對象     * @param type     * @param id     * @return     */    ActionTarget load(String type, Long id);}

按需要實現接口,樣例如下:JVU28資訊網——每日最新資訊28at.com

@Component@Order(0)public class TestActionTargetLoader        extends AbstractSingleActionTargetLoader        implements SingleActionTargetLoader {    public TestActionTargetLoader() {        super("Test");    }    @Override    protected ActionTarget doLoadById(String type, Long id) {        if (id == null || id.longValue() < 0){            return ActionTarget.apply(type, id, false);        }else {            return ActionTarget.apply(type, id);        }    }}

該實現對 type 為 Test 的 Target 進行加載。JVU28資訊網——每日最新資訊28at.com

4.2. 發布領域事件

領域事件是 DDD 中的重要概念,當系統發生狀態變化后,將變化結果對外進行廣播,從而實現系統間的集成。JVU28資訊網——每日最新資訊28at.com

4.2.1. 添加 RocketMQ

外部領域事件通過 RocketMQ 向外廣播,需要搭建 RocketMQ 集群并在項目中增加 RocketMQ 的支持。JVU28資訊網——每日最新資訊28at.com

在 bootstrap 模塊的 pom 中增加 rocketmq starter,具體如下:JVU28資訊網——每日最新資訊28at.com

<dependency>    <groupId>org.apache.rocketmq</groupId>    <artifactId>rocketmq-spring-boot-starter</artifactId></dependency>

在 application.yml 增加 rocketmq 的配置,具體如下:JVU28資訊網——每日最新資訊28at.com

rocketmq:  name-server: http://127.0.0.1:9876  producer:    group: like-service

至此,便完成了與 rocketmq 的集成。JVU28資訊網——每日最新資訊28at.com

4.2.2. 打開領域事件開關

在 application.yml 添加如下配置:JVU28資訊網——每日最新資訊28at.com

like:  event:    #開啟領域事件    enable: true    #指定領域事件發送的 topic    topic: like-event-topic

開啟領域事件,并指定事件發送的 topicJVU28資訊網——每日最新資訊28at.com

4.2.3. 測試領域事件

重新啟動項目,當控制臺輸出以下表明配置成功:JVU28資訊網——每日最新資訊28at.com

Use RocketMQ to Publish Like EventJVU28資訊網——每日最新資訊28at.com

使用 swagger 運行 dislike 操作,從日志中可知消息發送成功:JVU28資訊網——每日最新資訊28at.com

JVU28資訊網——每日最新資訊28at.com

4.2.4. 支持領域事件

系統支持的領域事件包括:JVU28資訊網——每日最新資訊28at.com

領域事件類型JVU28資訊網——每日最新資訊28at.com

觸發機制JVU28資訊網——每日最新資訊28at.com

tagJVU28資訊網——每日最新資訊28at.com

消息體JVU28資訊網——每日最新資訊28at.com

LikeMarkedEventJVU28資訊網——每日最新資訊28at.com

點贊成功JVU28資訊網——每日最新資訊28at.com

LikeMarkedEventJVU28資訊網——每日最新資訊28at.com

見 LikeMarkedEvent 類JVU28資訊網——每日最新資訊28at.com

LikeCancelledEventJVU28資訊網——每日最新資訊28at.com

取消點贊成功JVU28資訊網——每日最新資訊28at.com

LikeCancelledEventJVU28資訊網——每日最新資訊28at.com

見 LikeCancelledEvent 類JVU28資訊網——每日最新資訊28at.com

DislikeMarkedEventJVU28資訊網——每日最新資訊28at.com

踩成功JVU28資訊網——每日最新資訊28at.com

DislikeMarkedEventJVU28資訊網——每日最新資訊28at.com

見 DislikeMarkedEvent 類JVU28資訊網——每日最新資訊28at.com

DislikeCancelledEventJVU28資訊網——每日最新資訊28at.com

取消踩成功JVU28資訊網——每日最新資訊28at.com

DislikeCancelledEventJVU28資訊網——每日最新資訊28at.com

見 DislikeCancelledEvent 類JVU28資訊網——每日最新資訊28at.com

4.3. 緩存加速

在系統中,獲取目標對象的 贊/踩 數量接口調用量最大,會成為系統的第一個性能卡點,針對這個問題,可以通過引入 redis 緩存進行性能加速。JVU28資訊網——每日最新資訊28at.com

4.3.1. 添加 redis 依賴

首先需要引入 redis 相關依賴,在 bootstrap 的 pom 中增加如下配置:JVU28資訊網——每日最新資訊28at.com

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

然后在 application.yml 中增加 redis 相關配置:JVU28資訊網——每日最新資訊28at.com

spring:  redis:    host: 127.0.0.1    port: 6379

4.3.2. 開啟緩存

完成redis配置后,需要在 application.yml 開啟對應的緩存,具體如下:JVU28資訊網——每日最新資訊28at.com

target:  count:    dislike:      cache:        # 是否開啟緩存        enable: true    like:      cache:        # 是否開啟緩存        enable: true

4.3.3. 緩存效果

未開啟緩存前,每次查詢數量都會執行一條 sql,具體如下:curl 命令如下:JVU28資訊網——每日最新資訊28at.com

curl -X GET "http://127.0.0.1:8080/feignService/targetCount/query/getDislikeCountByType?type=test&ids=1" -H "accept: */*"

輸出 sql 如下:JVU28資訊網——每日最新資訊28at.com

Hibernate: select disliketar0_.id as id1_1_, disliketar0_.create_time as create_t2_1_, disliketar0_.delete_time as delete_t3_1_, disliketar0_.update_time as update_t4_1_, disliketar0_.vsn as vsn5_1_, disliketar0_.count as count6_1_, disliketar0_.target_id as target_i7_1_, disliketar0_.target_type as target_t8_1_ from dislike_target_count disliketar0_ where disliketar0_.target_type=? and (disliketar0_.target_id in (?))

開啟緩存后,再次執行以上 curl,控制臺不會輸出sql,而是會輸出一行日志:JVU28資訊網——每日最新資訊28at.com

c.g.l.i.s.RedisBasedTargetCountCache     : load All Data From Cache for test and [1]

說明緩存已經生效。JVU28資訊網——每日最新資訊28at.com

所有的 action 操作都會與同步的對緩存進行更新。JVU28資訊網——每日最新資訊28at.com

4.4. 異步存儲

當目標對象出現熱點時,會產生高并發請求,對于 action 來說,主要以數據插入和數據的分散更新為主。但對于 count,就會產生熱點更新,從而成為系統的瓶頸。在這個場景,最適合的解決方案便是引入 MQ 對流量進行削峰填谷。JVU28資訊網——每日最新資訊28at.com

4.4.1. 增加 rocketmq

與 4.2.1. 添加 RocketMQ 內容一致,在此不再重復。JVU28資訊網——每日最新資訊28at.com

4.4.2. 開啟異步化

在 application.yml 中增加如下配置:JVU28資訊網——每日最新資訊28at.com

target:  count:    dislike:      async:        # 是否開啟異步更新        enable: true        # 異步更新所使用的 topic        topic: dislike-target-count-async-topic        # 異步更新使用的消費者組        consumerGroup: dislike-target-count-async-group    like:      async:        # 是否開啟異步更新        enable: true        # 異步更新所使用的 topic        topic: like-target-count-async-topic        # 異步更新使用的消費者組        consumerGroup: like-target-count-async-group

4.4.3. 異步效果

重啟應用程序,在 swagger 中執行 點贊 操作,從控制臺可以看到如下日志:JVU28資訊網——每日最新資訊28at.com

[nio-8080-exec-7] c.g.l.c.a.order.OrderedAsyncInterceptor  : success to send orderly async Task to RocketMQ, args is [ActionTarget(type=test, id=18, valid=true), 1], shardingKey is 18, msg is GenericMessage [payload={"0":"{/"type/":/"test/",/"id/":18,/"valid/":true}","1":"1"}, headers={id=c84e6be5-acec-27c2-3f44-6250003a56c7, timestamp=1685275901638}], result is SendResult [sendStatus=SEND_OK, msgId=7F0000014F505C8DA9628F610AC60007, offsetMsgId=C0A8032300002A9F00000000001A0AFD, messageQueue=MessageQueue [topic=dislike-target-count-async-topic, brokerName=MacdeMacBook-Pro-171.local, queueId=3], queueOffset=8][MessageThread_4] g.l.i.d.DislikeTargetCountRepositoryImpl : begin to incr for db target ActionTarget(type=test, id=18, valid=true), count 1[nio-8080-exec-7] com.geekhalo.like.app.RocketMQPublisher  : success to send msg GenericMessage [payload={"targetId":18,"targetType":"test","userId":1}, headers={id=4e8e13f9-b3cd-7b90-059f-f506f09d9948, timestamp=1685275901640}] to like-event-topic:DislikeMarkedEvent, msgId is 7F0000014F505C8DA9628F610AC80008[nio-8080-exec-7] c.g.l.c.c.s.AbstractCommandService       : success to sync AbstractCommandService.Syncer.Data(id=106, action=UPDATE, a=DislikeAction(super=AbstractAction(super=AbstractAggRoot(super=AbstractEntity(vsn=0, createAt=Sun May 28 20:11:41 CST 2023, updateAt=Sun May 28 20:11:41 CST 2023, deleteAt=null), events=[]), id=106, user=ActionUser(userId=1, valid=true), target=ActionTarget(type=test, id=18, valid=true), status=VALID)))[MessageThread_4] g.l.i.d.DislikeTargetCountRepositoryImpl : success to incr for db target ActionTarget(type=test, id=18, valid=true), count 1[MessageThread_4] .s.AbstractSingleMethodConsumerContainer : consume message 7F0000014F505C8DA9628F610AC60007, cost: 27 ms

從日志上看,可以得出:JVU28資訊網——每日最新資訊28at.com

  • nio 線程向 MQ 發送消息
  • MessageThread 線程從 MQ 中獲取數據并執行 incr 操作

4.5. 分庫分表

隨著系統的運行,數據量會逐漸增大,最終超出單個 DB 的容量上限。這種情況下,最佳實踐便是對數據庫進行分庫分表。JVU28資訊網——每日最新資訊28at.com

4.5.1. 構建數據庫和表

在 infrastructure 模塊的 sql 目錄下存在兩個 sql 文件:JVU28資訊網——每日最新資訊28at.com

  • create_table_sharding_action.sql : 贊/踩 操作分庫分表
  • create_table_sharding_count.sql : 贊/踩 計數分庫分表

示例中總共分16張表,存放在兩個數據庫中:JVU28資訊網——每日最新資訊28at.com

  • db1 存放 0-7 表
  • db2 存放 8-15 表

如圖所示:JVU28資訊網——每日最新資訊28at.com

4.5.2. 添加 ShardingSphere 支持

在 bootstrap 的pom 文件增加 ShardingSphere 的依賴,具體如下:JVU28資訊網——每日最新資訊28at.com

<dependency>    <groupId>org.apache.shardingsphere</groupId>    <artifactId>sharding-jdbc-spring-boot-starter</artifactId></dependency>

其次,增加分庫分表配置文件,為了方便新建 application.properties 存放分庫分表配置:JVU28資訊網——每日最新資訊28at.com

# 數據源配置# 總共4個數據源spring.shardingsphere.datasource.names=action-ds0, action-ds1, count-ds0, count-ds1 # action-ds0 數據源配置spring.shardingsphere.datasource.action-ds0.type=com.zaxxer.hikari.HikariDataSourcespring.shardingsphere.datasource.action-ds0.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.action-ds0.jdbc-url=jdbc:mysql://127.0.0.1:3306/like_action_0?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTCspring.shardingsphere.datasource.action-ds0.username=rootspring.shardingsphere.datasource.action-ds0.password=root# action-ds1 數據源配置spring.shardingsphere.datasource.action-ds1.type=com.zaxxer.hikari.HikariDataSourcespring.shardingsphere.datasource.action-ds1.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.action-ds1.jdbc-url=jdbc:mysql://127.0.0.1:3306/like_action_1?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTCspring.shardingsphere.datasource.action-ds1.username=rootspring.shardingsphere.datasource.action-ds1.password=root# count-ds0 數據源配置spring.shardingsphere.datasource.count-ds0.type=com.zaxxer.hikari.HikariDataSourcespring.shardingsphere.datasource.count-ds0.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.count-ds0.jdbc-url=jdbc:mysql://127.0.0.1:3306/like_count_0?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTCspring.shardingsphere.datasource.count-ds0.username=rootspring.shardingsphere.datasource.count-ds0.password=root# count-ds1 數據源配置spring.shardingsphere.datasource.count-ds1.type=com.zaxxer.hikari.HikariDataSourcespring.shardingsphere.datasource.count-ds1.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.count-ds1.jdbc-url=jdbc:mysql://127.0.0.1:3306/like_count_1?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTCspring.shardingsphere.datasource.count-ds1.username=rootspring.shardingsphere.datasource.count-ds1.password=root# 分庫分表規則配置# 使用雪花算法生成分布式主鍵id的值spring.shardingsphere.sharding.default-key-generator.column=idspring.shardingsphere.sharding.default-key-generator.column-type=BIGINTspring.shardingsphere.sharding.default-key-generator.type=SNOWFLAKEspring.shardingsphere.sharding.default-key-generator.algorithm-expression=SNOWFLAKE_HASH(id, 12)spring.shardingsphere.sharding.default-key-generator.matrix-handling-type=SHARDING_DEFAULT# 踩行為表配置spring.shardingsphere.sharding.tables.dislike_action.actual-data-nodes=action-ds0.dislike_action_$->{0..7},action-ds1.dislike_action_$->{8..15}# user_id 為分表分片鍵spring.shardingsphere.sharding.tables.dislike_action.table-strategy.inline.sharding-column=user_id# 根據 user_id 以 16 取模,進行分表spring.shardingsphere.sharding.tables.dislike_action.table-strategy.inline.algorithm-expression=dislike_action_$->{Math.abs(user_id.hashCode())  % 16}# user_id 為分庫分片鍵spring.shardingsphere.sharding.tables.dislike_action.database-strategy.inline.sharding-column=user_id# 根據 user_id 以 16 取模后除8 ,進行分庫spring.shardingsphere.sharding.tables.dislike_action.database-strategy.inline.algorithm-expression=action-ds$->{Math.floorDiv((Math.abs(user_id.hashCode())  % 16) , 8)}spring.shardingsphere.sharding.tables.like_action.actual-data-nodes=action-ds0.like_action_$->{0..7},action-ds1.like_action_$->{8..15}spring.shardingsphere.sharding.tables.like_action.table-strategy.inline.sharding-column=user_idspring.shardingsphere.sharding.tables.like_action.table-strategy.inline.algorithm-expression=like_action_$->{Math.abs(user_id.hashCode())  % 16}spring.shardingsphere.sharding.tables.like_action.database-strategy.inline.sharding-column=user_idspring.shardingsphere.sharding.tables.like_action.database-strategy.inline.algorithm-expression=action-ds$->{Math.floorDiv((Math.abs(user_id.hashCode())  % 16) , 8)}# 計數表配置spring.shardingsphere.sharding.tables.dislike_target_count.actual-data-nodes=count-ds0.dislike_target_count_$->{0..7},count-ds1.dislike_target_count_$->{8..15}# target_id 為分表分片鍵spring.shardingsphere.sharding.tables.dislike_target_count.table-strategy.inline.sharding-column=target_id# 根據 target_id 以 16 取模,進行分表spring.shardingsphere.sharding.tables.dislike_target_count.table-strategy.inline.algorithm-expression=dislike_target_count_$->{Math.abs(target_id.hashCode())  % 16}# target_id 為分庫分片鍵spring.shardingsphere.sharding.tables.dislike_target_count.database-strategy.inline.sharding-column=target_id# 根據 target_id 以 16 取模后除8 ,進行分庫spring.shardingsphere.sharding.tables.dislike_target_count.database-strategy.inline.algorithm-expression=count-ds$->{Math.floorDiv((Math.abs(target_id.hashCode()) % 16), 8)}spring.shardingsphere.sharding.tables.like_target_count.actual-data-nodes=count-ds0.like_target_count_$->{0..7},count-ds1.like_target_count_$->{8..15}spring.shardingsphere.sharding.tables.like_target_count.table-strategy.inline.sharding-column=target_idspring.shardingsphere.sharding.tables.like_target_count.table-strategy.inline.algorithm-expression=like_target_count_$->{Math.abs(target_id.hashCode()) % 16}spring.shardingsphere.sharding.tables.like_target_count.database-strategy.inline.sharding-column=target_idspring.shardingsphere.sharding.tables.like_target_count.database-strategy.inline.algorithm-expression=count-ds$->{Math.floorDiv((Math.abs(target_id.hashCode()) % 16), 8)}# 打印 SQL 配置(可選)spring.shardingsphere.props.sql.show=true

在雪花算法情況下,尾數會變的極度不均勻,所以在進行計算之前,通常先執行 hashCode 在進行取模操作。JVU28資訊網——每日最新資訊28at.com

4.5.3. 分庫分表效果

啟動應用程序,控制臺輸出 sharding 相關配置,具體如下:JVU28資訊網——每日最新資訊28at.com

defaultKeyGenerator:  column: id  type: SNOWFLAKEtables:  dislike_action:    actualDataNodes: action-ds0.dislike_action_$->{0..7},action-ds1.dislike_action_$->{8..15}    databaseStrategy:      inline:        algorithmExpression: action-ds$->{Math.floorDiv((Math.abs(user_id.hashCode())  % 16) , 8)}        shardingColumn: user_id    logicTable: dislike_action    tableStrategy:      inline:        algorithmExpression: dislike_action_$->{Math.abs(user_id.hashCode()) % 16}        shardingColumn: user_id  like_action:    actualDataNodes: action-ds0.like_action_$->{0..7},action-ds1.like_action_$->{8..15}    databaseStrategy:      inline:        algorithmExpression: action-ds$->{Math.floorDiv((Math.abs(user_id.hashCode())  % 16) , 8)}        shardingColumn: user_id    logicTable: like_action    tableStrategy:      inline:        algorithmExpression: like_action_$->{Math.abs(user_id.hashCode())  % 16}        shardingColumn: user_id  dislike_target_count:    actualDataNodes: count-ds0.dislike_target_count_$->{0..7},count-ds1.dislike_target_count_$->{8..15}    databaseStrategy:      inline:        algorithmExpression: count-ds$->{Math.floorDiv((Math.abs(target_id.hashCode()) % 16), 8)}        shardingColumn: target_id    logicTable: dislike_target_count    tableStrategy:      inline:        algorithmExpression: dislike_target_count_$->{Math.abs(target_id.hashCode())  % 16}        shardingColumn: target_id  like_target_count:    actualDataNodes: count-ds0.like_target_count_$->{0..7},count-ds1.like_target_count_$->{8..15}    databaseStrategy:      inline:        algorithmExpression: count-ds$->{Math.floorDiv((Math.abs(target_id.hashCode()) % 16), 8)}        shardingColumn: target_id    logicTable: like_target_count    tableStrategy:      inline:        algorithmExpression: like_target_count_$->{Math.abs(target_id.hashCode()) % 16}        shardingColumn: target_id

在 Swagger UI 中操作點贊,控制臺輸出如下:JVU28資訊網——每日最新資訊28at.com

Logic SQL: select dislikeact0_.id as id1_0_, dislikeact0_.create_time as create_t2_0_, dislikeact0_.delete_time as delete_t3_0_, dislikeact0_.update_time as update_t4_0_, dislikeact0_.vsn as vsn5_0_, dislikeact0_.status as status6_0_, dislikeact0_.target_id as target_i7_0_, dislikeact0_.target_type as target_t8_0_, dislikeact0_.user_id as user_id9_0_ from dislike_action dislikeact0_ where dislikeact0_.user_id=? and dislikeact0_.target_type=?Actual SQL: action-ds0 ::: select dislikeact0_.id as id1_0_, dislikeact0_.create_time as create_t2_0_, dislikeact0_.delete_time as delete_t3_0_, dislikeact0_.update_time as update_t4_0_, dislikeact0_.vsn as vsn5_0_, dislikeact0_.status as status6_0_, dislikeact0_.target_id as target_i7_0_, dislikeact0_.target_type as target_t8_0_, dislikeact0_.user_id as user_id9_0_ from dislike_action_0 dislikeact0_ where dislikeact0_.user_id=? and dislikeact0_.target_type=? ::: [2707692781417059328, Test]

其中:JVU28資訊網——每日最新資訊28at.com

  • Logic SQL:邏輯 SQL 中的表為 dislike_action
  • Actual SQL:實際執行的 SQL 表為 dislike_action_0,數據庫為 action-ds0

5. 項目信息

項目地址見:https://gitee.com/litao851025/lego/tree/master/services/likeJVU28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-15743-0.html基于 DDD 的互聯網“贊&amp;踩”系統

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: Spring 冷知識:一個提前 AOP 的機會

下一篇: Openjdk Btrace--追蹤你的程序

標簽:
  • 熱門焦點
  • MIX Fold3包裝盒泄露 新機本月登場

    小米的全新折疊屏旗艦MIX Fold3將于本月發布,近日該機的真機包裝盒在網上泄露。從圖上來看,新的MIX Fold3包裝盒在外觀設計方面延續了之前的方案,變化不大,這也是目前小米旗艦
  • 轎車從天而降電動車主被撞身亡 超速搶道所致:現場視頻讓網友吵翻

    近日,上海青浦區法院判決轎車從天而降電動車主被撞身亡案,轎車車主被判有期徒刑一年。案件顯示當時男子駕駛轎車在上海某路段行駛,前車忽然轉彎提速超車,
  • 線程通訊的三種方法!通俗易懂

    線程通信是指多個線程之間通過某種機制進行協調和交互,例如,線程等待和通知機制就是線程通訊的主要手段之一。 在 Java 中,線程等待和通知的實現手段有以下幾種方式:Object 類下
  • 服務存儲設計模式:Cache-Aside模式

    Cache-Aside模式一種常用的緩存方式,通常是把數據從主存儲加載到KV緩存中,加速后續的訪問。在存在重復度的場景,Cache-Aside可以提升服務性能,降低底層存儲的壓力,缺點是緩存和底
  • 破圈是B站頭上的緊箍咒

    來源 | 光子星球撰文 | 吳坤諺編輯 | 吳先之每年的暑期檔都少不了瞄準追劇女孩們的古偶劇集,2021年有優酷的《山河令》,2022年有愛奇藝的《蒼蘭訣》,今年卻輪到小破站抓住了追
  • 網紅炒股不為了賺錢,那就是耍流氓!

    來源:首席商業評論6月26日高調宣布入市,網絡名嘴大v胡錫進居然進軍了股市。在一次財經媒體峰會上,幾個財經圈媒體大佬就&ldquo;胡錫進炒股是否知道認真報道&rdquo;展開討論。有
  • 7月4日見!iQOO 11S官宣:“雞血版”驍龍8 Gen2+200W快充加持

    上半年已接近尾聲,截至目前各大品牌旗下的頂級旗艦都已悉數亮相,而下半年即將推出的頂級旗艦已經成為了數碼圈爆料的主流,其中就包括全新的iQOO 11S系
  • 機構稱Q2全球智能手機出貨量同比下滑11% 蘋果份額依舊第2

    7月20日消息,據外媒報道,研究機構的報告顯示,由于需求下滑,今年二季度全球智能手機的出貨量,同比下滑了11%,三星、蘋果等主要廠商的銷量,較去年同期均有下
  • 三翼鳥智能家居亮相電博會,讓用戶體驗更真實

    2021電博會在青島國際會展中心開幕中,三翼鳥直接把“家”搬到了現場,成為了展會的一大看點。這也是三翼鳥繼9月9日發布了行業首個一站式定制智慧家平臺后的
Top