主頁 > 後端開發 > 有來實驗室|第一篇:Seata1.5.2版本部署和開源全堆疊商城訂單支付業務實戰

有來實驗室|第一篇:Seata1.5.2版本部署和開源全堆疊商城訂單支付業務實戰

2022-12-05 12:12:31 後端開發

在線體驗:Seata實驗室

一. 前言

相信 youlai-mall 的實驗室大家有曾在專案中見到過,但應該都還處于陌生的階段,畢竟在此之前實驗室多是以概念般的形式存在,所以我想借著此次的機會,對其進行一個詳細的說明,

實驗室模塊的建立初衷和開源專案的成立一致的,都是為了提升開發成員的技術能力,只不過開源專案是從技術堆疊廣度上(全堆疊),而實驗室則是從技術堆疊深度方面切入,更重要的它是一種更深刻而又高效的學習方式,為什么能夠這么說?因為實驗室是結合真實的業務場景把中間件的作用可視化出來,達到通過現象去看本質(原理和原始碼)的目的,再也不是被動式輸入的短期記憶學習,

實驗室未來計劃是將作業和面試常見的中間件(Spring、MyBatis、Redis、Seata、MQ、MySQL、ES等)做進來,本篇就以 Seata 為例正式為有來實驗室拉開一個序幕,

二. Seata 概念

Seata 是一款開源的分布式事務解決方案,致力于提供高性能和簡單易用的分布式事務服務,Seata 將為用戶提供了 AT、TCC、SAGA 和 XA 事務模式,為用戶打造一站式的分布式解決方案,

術語
TC (Transaction Coordinator) - 事務協調者 維護全域和分支事務的狀態,驅動全域事務提交或回滾,
TM (Transaction Manager) - 事務管理器 定義全域事務的范圍:開始全域事務、提交或回滾全域事務,
RM (Resource Manager) - 資源管理器 管理分支事務處理的資源,與TC交談以注冊分支事務和報告分支事務的狀態,并驅動分支事務提交或回滾,

三. Seata 服務端部署

中間件宣告

中間件 版本 服務器IP
Seata 1.5.2 192.168.10.100 8091、7091
Nacos 2.0.3 192.168.10.99 8848
MySQL 8.0.27 192.168.10.98 3306

官方鏈接

名稱 地址
檔案 http://seata.io/zh-cn/
原始碼 https://github.com/seata/seata
MySQL腳本 https://github.com/seata/seata/blob/1.5.2/script/server/db/mysql.sql
Seata外置配置 https://github.com/seata/seata/blob/1.5.2/script/config-center/config.txt

Seata 資料庫

Seata 表結構MySQL腳本在線地址: https://github.com/seata/seata/blob/1.5.2/script/server/db/mysql.sql

執行以下腳本完成 Seata 資料庫創建和表的初始化:

-- 1. 執行陳述句創建名為 seata 的資料庫
CREATE DATABASE seata DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;

-- 2.執行腳本完成 Seata 表結構的創建
use seata;

-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(128),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_status` (`status`),
    KEY `idx_branch_id` (`branch_id`),
    KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS `distributed_lock`
(
    `lock_key`       CHAR(20) NOT NULL,
    `lock_value`     VARCHAR(20) NOT NULL,
    `expire`         BIGINT,
    primary key (`lock_key`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);

Seata 配置

這里采用 Nacos 作為配置中心的方式,所以需要把 Seata 的外置配置 放置在Nacos上

1. 獲取 Seata 外置配置

獲取Seata 配置在線地址:https://github.com/seata/seata/blob/1.5.2/script/config-center/config.txt

完整配置如下:

#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
transport.serialization=seata
transport.compressor=none

#Transaction routing rules configuration, only for the client
service.vgroupMapping.default_tx_group=default
#If you use a registry, you can ignore it
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false

#Transaction rule configuration, only for the client
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=true
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.rm.sagaJsonParser=fastjson
client.rm.tccActionInterceptorOrder=-2147482648
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
client.tm.interceptorOrder=-2147482648
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h

#Log rule configuration, for client and server
log.exceptionRate=100

#Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
store.mode=file
store.lock.mode=file
store.session.mode=file
#Used for password encryption
store.publicKey=

#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100

#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=username
store.db.password=password
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000

#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100

#Transaction rule configuration, only for the server
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false

#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

2. 匯入配置至 Nacos

在 Nacos 默認的 public 命名空間下 ,新建配置 Data ID 為 seataServer.properties ,Group 為 SEATA_GROUP 的配置

image-20221124235041087

image-20221124235347673

3. 修改 Seata 外置配置

把默認 Seata 全量配置匯入 Nacos 之后,本篇這里僅需修存盤模式為db以及對應的db連接配置

# 修改store.mode為db,配置資料庫連接
store.mode=db
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.10.98:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
  • **store.mode=db **存盤模式選擇為資料庫
  • 192.168.10.98 MySQL主機地址
  • store.db.user=root 資料庫用戶名
  • store.db.password=123456 資料庫密碼

Seata 部署

Seata 官方部署檔案:https://seata.io/zh-cn/docs/ops/deploy-by-docker.html

1. 獲取應用配置

按照官方檔案描述使用自定義組態檔的部署方式,需要先創建臨時容器把配置copy到宿主機

創建臨時容器

docker run -d --name seata-server -p 8091:8091 -p 7091:7091 seataio/seata-server:1.5.2

創建掛載目錄

mkdir -p /mnt/seata/config

復制容器配置至宿主機

docker cp seata-server:/seata-server/resources/ /mnt/seata/config

注意復制到宿主機的目錄,下文啟動容器需要做宿主機和容器的目錄掛載

image-20221126122442156

過河拆橋,洗掉臨時容器

docker rm -f seata-server

2. 修改啟動配置

在獲取到 seata-server 的應用配置之后,因為這里采用 Nacos 作為 seata 的配置中心和注冊中心,所以需要修改 application.yml 里的配置中心和注冊中心地址,詳細配置我們可以從 application.example.yml 拿到,

application.yml 原配置

image-20221126103400571

修改后的配置(參考 application.example.yml 示例檔案),以下是需要調整的部分,其他配置默認即可

seata:
  config:
    type: nacos
    nacos:
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP
      data-id: seataServer.properties
  registry:
    type: nacos
    preferred-networks: 30.240.*
    nacos:
      application: seata-server
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP
      cluster: default
  # 存盤模式在外置配置(Nacos)中,Nacos 配置加載優先級大于application.yml,會被application.yml覆寫,所以此處注釋
  #store:
  	#mode: file
  • **192.168.10.99 ** 是Nacos宿主機的IP地址,Docker部署別錯填 localhost 或Docker容器的IP(172.17. * . *)
  • namespace nacos命名空間id,不填默認是public命名空間
  • data-id: seataServer.properties Seata外置檔案所處Naocs的Data ID,參考上小節的 匯入配置至 Nacos
  • group: SEATA_GROUP 指定注冊至nacos注冊中心的分組名
  • cluster: default 指定注冊至nacos注冊中心的集群名

3. 啟動容器

docker run -d --name seata-server --restart=always  \
-p 8091:8091 \
-p 7091:7091 \
-e SEATA_IP=192.168.10.100 \
-v /mnt/seata/config:/seata-server/resources \
seataio/seata-server:1.5.2 
  • /mnt/seata/config Seata應用配置掛載在宿主機的目錄

  • 192.168.10.100 Seata 宿主機IP地址

在 nacos 控制臺 的 public 命名空間下服務串列里有 seata-server 說明部署啟動成功

image-20221126123623622

如果啟動失敗或者未注冊到 nacos , 基本是粗心的結果,請仔細檢查下自己 application.yml 的注冊中心配置或查看日志

 docker logs -f --tail=100 seata-server

以上就完成對 Seata 服務端的部署和配置,接下來就是 SpringBoot 與 Seata 客戶端的整合,

四. Seata 客戶端搭建

1. Maven 依賴

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <!-- 默認seata客戶端版本比較低,排除后重新引入指定版本-->
    <exclusions>
        <exclusion>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.5.2</version>
</dependency>

2. undo_log 表

undo_log表腳本: https://github.com/seata/seata/blob/1.5.2/script/client/at/db/mysql.sql

-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
    `xid`           VARCHAR(128) NOT NULL COMMENT 'global transaction id',
    `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
    `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
    `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
    `log_created`   DATETIME(6)  NOT NULL COMMENT 'create datetime',
    `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
    UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8mb4 COMMENT ='AT transaction mode undo table';

AT模式兩階段提交協議的演變:

  • 一階段:業務資料和回滾日志記錄在同一個本地事務中提交,釋放本地鎖和連接資源,
  • 二階段:
    • 提交異步化,非常快速地完成,
    • 回滾通過一階段的回滾日志進行反向補償,

Seata的AT模式下之所以在第一階段直接提交事務,依賴的是需要在每個RM創建一張undo_log表,記錄業務執行前后的資料快照,

如果二階段需要回滾,直接根據undo_log表回滾,如果執行成功,則在第二階段洗掉對應的快照資料,

3. 客戶端配置

# Seata配置
seata:
  enabled: true
  # 指定事務分組至集群映射關系,集群名default需要與seata-server注冊到Nacos的cluster保持一致
  service:
    vgroup-mapping:
      mall_tx_group: default 
  # 事務分組配置
  tx-service-group: mall_tx_group
  registry:
    type: nacos
    nacos:
      application: seata-server
      # nacos 服務地址
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP

以上3點就是 Seata 客戶端需要做的事項,下面就 Seata 如何實戰應用進行展開詳細說明,

五. Seata 實戰

Seata 官網示例: http://seata.io/zh-cn/docs/user/quickstart.html

需求

用戶購買商品訂單支付的業務邏輯,整個業務邏輯由3個微服務提供支持:

  • 商品服務:扣減商品庫存,
  • 訂單服務:修改訂單狀態【已支付】,
  • 會員服務:扣減賬戶余額,

架構圖

  • TM:事務管理器(有來實驗室:laboratory)
  • RM:資源管理器(商城服務:mall-pms;會員服務:mall-ums;訂單服務:mall-oms)
  • TC :事務協調者(Seata服務端:seata-server)

代碼實作

有來實驗室

實驗室在“訂單支付”案例中扮演的是【事務管理器】的角色,其作業內容是開始全域事務、提交或回滾全域事務,

按照 【第三節-Seata客戶端搭建 】 在 laboratory 模塊添加 Maven 依賴和客戶端的配置,

訂單支付關鍵代碼片段(SeataServiceImpl#payOrderWithGlobalTx),通過注解 GlobalTransactional 開啟全域事務,通過對商品 Feign 客戶端和訂單 Feign 客戶端的呼叫完成訂單支付的流程,這是全域事務開始的地方,


    /**
     * 訂單支付(全域事務)
     */
    @GlobalTransactional
    public boolean payOrderWithGlobalTx(SeataForm seataForm) {

        log.info("========扣減商品庫存========");
        skuFeignClient.deductStock(skuId, 1); 

        log.info("========訂單支付========");
        orderFeignClient.payOrder(orderId, ...);

        return true;
    }

商品服務

按照 【第三節-Seata客戶端搭建 】 在 mall-pms 模塊添加 Maven 依賴和客戶端的配置,在 mall-pms 資料庫創建 undo_log 表,

扣減庫存關鍵代碼:

    /**
     * 「實驗室」扣減商品庫存
     */
    public boolean deductStock(Long skuId, Integer num) {
        boolean result = this.update(new LambdaUpdateWrapper<PmsSku>()
                .setSql("stock_num = stock_num - " + num)
                .eq(PmsSku::getId, skuId)
        );
        return result;
    }

訂單服務

按照 【第三節-Seata客戶端搭建 】 在 mall-oms 模塊添加 Maven 依賴和客戶端的配置,在 mall-oms 資料庫創建 undo_log 表,

訂單支付關鍵代碼:

    /**
     * 「實驗室」訂單支付
     */
    public Boolean payOrder(Long orderId, SeataOrderDTO orderDTO) {

        Long memberId = orderDTO.getMemberId();
        Long amount = orderDTO.getAmount();

        // 扣減賬戶余額
        memberFeignClient.deductBalance(memberId, amount);

        // 【關鍵】如果開啟例外,全域事務將會回滾
        Boolean openEx = orderDTO.getOpenEx();
        if (openEx) {
            int i = 1 / 0;
        }

        // 修改訂單【已支付】
        boolean result = this.update(new LambdaUpdateWrapper<OmsOrder>()
                .eq(OmsOrder::getId, orderId)
                .set(OmsOrder::getStatus, OrderStatusEnum.WAIT_SHIPPING.getValue())
        );

        return result;
    }

會員服務

按照 【第三節-Seata客戶端搭建 】 在 mall-ums 模塊添加 Maven 依賴和客戶端的配置,在 mall-ums 資料庫創建 undo_log 表,

扣減余額關鍵代碼:

    @ApiOperation(value = "https://www.cnblogs.com/haoxianrui/archive/2022/12/05/「實驗室」扣級訓員余額")
    @PutMapping("/{memberId}/balances/_deduct")
    public Result deductBalance(@PathVariable Long memberId, @RequestParam Long amount) {
        boolean result = memberService.update(new LambdaUpdateWrapper<UmsMember>()
                .setSql("balance = balance - " + amount)
                .eq(UmsMember::getId, memberId));
        return Result.judge(result);
    }

測驗

以上就基于 youlai-mall 商城訂單支付的業務簡單實作的 Seata 實驗室,接下來通過測驗來看看 Seata 分布式事務的能力,

未開啟事務

未開啟事務前提: 訂單狀態因為例外修改失敗,但這并未影響到商品庫存扣減和余額扣減成功的結果,明顯這不是希望的結果,

image-20221204163239115

開啟事務

開啟事務前提:訂單狀態修改發生例外,同時也回滾了扣減庫存、扣減余額的行為,可見 Seata 分布式事務生效,

image-20221204163205891

六. Seata 原始碼

因為 Seata 原始碼牽涉角色比較多,需要在本地搭建 seata-server 然后和 Seata 客戶端互動除錯,后面整理出來會單獨拿一篇文章進行進行具體分析,

image-20221204222607903

七. 結語

本篇通過 Seata 1.5.2 版本部署到實戰講述了 Seata 分布式事務AT模式在商城訂單支付業務場景的應用,相信大家對 Seata 和有來實驗室有個初步的認知,但這里還只是一個開始,后續會有更多的熱門中間件登上實驗室舞臺,當然,可見這個舞臺很大,所以也希望有興趣或者有想法同學加入有來實驗室的開發,

附. 原始碼

本文原始碼已推送至gitee和github倉庫

gitee github
后端工程 https://gitee.com/youlaitech/youlai-mall https://github.com/youlaitech/youlai-mall
前端工程 https://gitee.com/youlaiorg/mall-admin https://github.com/youlaitech/mall-admin

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539210.html

標籤:其他

上一篇:每日演算法之二叉搜索樹的后序遍歷序列

下一篇:Java8新特性之方法參考

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more