SaaS平台开发实战(二):基础服务模块

在上一章中,我们安装了测试服务器的服务,安装了idea,创建项目并完成了maven相关项目的引用。

这一章我们将在nacos中创建基础服务模块各种配置,在创建之前,建议先在nginx中配置nacos以便我们可以在web中进行访问。

在配置基础服务模块前,先添加seata的配置

添加seata-server.properties配置

注意Group是SEATA_GROUP

  1 transport.type=TCP
  2 transport.server=NIO
  3 transport.heartbeat=true
  4 transport.enableTmClientBatchSendRequest=false
  5 transport.enableRmClientBatchSendRequest=true
  6 transport.enableTcServerBatchSendResponse=false
  7 transport.rpcRmRequestTimeout=30000
  8 transport.rpcTmRequestTimeout=30000
  9 transport.rpcTcRequestTimeout=30000
 10 transport.threadFactory.bossThreadPrefix=NettyBoss
 11 transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
 12 transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
 13 transport.threadFactory.shareBossWorker=false
 14 transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
 15 transport.threadFactory.clientSelectorThreadSize=1
 16 transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
 17 transport.threadFactory.bossThreadSize=1
 18 transport.threadFactory.workerThreadSize=default
 19 transport.shutdown.wait=3
 20 transport.serialization=seata
 21 transport.compressor=none
 22 
 23 
 24 #Transaction routing rules configuration, only for the client
 25 service.vgroupMapping.tx_user_group=default
 26 service.vgroupMapping.tx_order_group=default
 27 service.vgroupMapping.tx_marketing_group=default
 28 service.vgroupMapping.tx_master_group=default
 29 service.vgroupMapping.tx_delivery_group=default
 30 service.vgroupMapping.tx_storage_group=default
 31 
 32 #If you use a registry, you can ignore it
 33 service.default.grouplist=xxx.com:28092
 34 service.enableDegrade=false
 35 service.disableGlobalTransaction=false
 36 
 37 #Transaction rule configuration, only for the client
 38 client.rm.asyncCommitBufferLimit=10000
 39 client.rm.lock.retryInterval=10
 40 client.rm.lock.retryTimes=30
 41 client.rm.lock.retryPolicyBranchRollbackOnConflict=true
 42 client.rm.reportRetryCount=5
 43 client.rm.tableMetaCheckEnable=true
 44 client.rm.tableMetaCheckerInterval=60000
 45 client.rm.sqlParserType=druid
 46 client.rm.reportSuccessEnable=false
 47 client.rm.sagaBranchRegisterEnable=false
 48 client.rm.sagaJsonParser=fastjson
 49 client.rm.tccActionInterceptorOrder=-2147482648
 50 client.tm.commitRetryCount=5
 51 client.tm.rollbackRetryCount=5
 52 client.tm.defaultGlobalTransactionTimeout=60000
 53 client.tm.degradeCheck=false
 54 client.tm.degradeCheckAllowTimes=10
 55 client.tm.degradeCheckPeriod=2000
 56 client.tm.interceptorOrder=-2147482648
 57 client.undo.dataValidation=true
 58 client.undo.logSerialization=jackson
 59 client.undo.onlyCareUpdateColumns=true
 60 server.undo.logSaveDays=7
 61 server.undo.logDeletePeriod=86400000
 62 client.undo.logTable=undo_log
 63 client.undo.compress.enable=true
 64 client.undo.compress.type=zip
 65 client.undo.compress.threshold=64k
 66 #For TCC transaction mode
 67 tcc.fence.logTableName=tcc_fence_log
 68 tcc.fence.cleanPeriod=1h
 69 
 70 #Log rule configuration, for client and server
 71 log.exceptionRate=100
 72 
 73 #Transaction storage configuration, only for the server. The file, db, and redis configuration values are optional.
 74 store.mode=db
 75 store.lock.mode=db
 76 store.session.mode=db
 77 
 78 
 79 #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.
 80 store.db.datasource=druid
 81 store.db.dbType=mysql
 82 store.db.driverClassName=com.mysql.jdbc.Driver
 83 store.db.url=jdbc:mysql://127.0.0.1:3333/seata?useUnicode=true&rewriteBatchedStatements=true
 84 store.db.user=seata
 85 store.db.password=xxxxx
 86 store.db.minConn=5
 87 store.db.maxConn=30
 88 store.db.globalTable=global_table
 89 store.db.branchTable=branch_table
 90 store.db.distributedLockTable=distributed_lock
 91 store.db.queryLimit=100
 92 store.db.lockTable=lock_table
 93 store.db.maxWait=5000
 94 
 95 
 96 #Transaction rule configuration, only for the server
 97 server.recovery.committingRetryPeriod=1000
 98 server.recovery.asynCommittingRetryPeriod=1000
 99 server.recovery.rollbackingRetryPeriod=1000
100 server.recovery.timeoutRetryPeriod=1000
101 server.maxCommitRetryTimeout=-1
102 server.maxRollbackRetryTimeout=-1
103 server.rollbackRetryTimeoutUnlockEnable=false
104 server.distributedLockExpireTime=10000
105 server.xaerNotaRetryTimeout=60000
106 server.session.branchAsyncQueueSize=5000
107 server.session.enableBranchAsyncRemove=false
108 server.enableParallelRequestHandle=false
109 
110 #Metrics configuration, only for the server
111 metrics.enabled=false
112 metrics.registryType=compact
113 metrics.exporterList=prometheus
114 metrics.exporterPrometheusPort=9898
View Code

 

service.vgroupMapping,service.default.grouplist,store.db请根据您自身进行配置

修改服务器seata配置

vim seata dir/conf/application.yml

#  Copyright 1999-2019 Seata.io Group.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

server:
  port: 7091

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: xxxx
    password: xxxx

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: nacos #file
    nacos:
        # 替换成您自己的nacos配置
        server-addr: localhost:18888
        namespace: xxxxx-xx-xx-xx-xxxx
        group: SEATA_GROUP
        username: xxxx
        password: xxxx
        data-id: seata-server.properties
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    nacos:
        server-addr: localhost:18888
        namespace: xxxx-xxx-xxx-xxxx
        group: SEATA_GROUP
        username: xxxx
        password: xxxx
        cluster: default
  store:
    # support: file 、 db 、 redis
    mode: db
    db:
      datasource: druid
      db-type: mysql
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3333/xxx?rewriteBatchedStatements=true&useUnicode=true
      user: xxxx
      password: xxxxxxxxxxxxxx
      min-conn: 5
      max-conn: 100
      global-table: global_table
      branch-table: branch_table
      lock-table: lock_table
      distributed-lock-table: distributed_lock
      query-limit: 100
      max-wait: 5000
#   server:
#     service-port: 28093 #If not configured, the default is '${server.port} + 1000'
  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login

 

配置文件中涉及IP、端口、用户名、密码等均替换成您自己的即可。

配置命名空间

在nacos中创建如图命名空间

创建multienty.yaml配置

创建multienty.yaml配置
 1 spring:
 2     main:
 3         allow-bean-definition-overriding: true
 4     cloud:
 5         sentinel:
 6             enabled: false
 7             eager: true
 8             transport:
 9                 dashboard: sentinel.xxx.cn:32465
10     flyway:
11         enabled: false
12         locations: classpath:db/migration
13         validate-on-migrate: true
14         clean-disabled: true
15         baseline-on-migrate: true
16         extensions:
17             location-prefix: classpath:db/migration/
18     datasource:
19         type: com.alibaba.druid.pool.DruidDataSource
20         dynamic:
21             strict: false
22             druid:
23                 initialSize: 1
24                 minIdle: 3
25                 maxActive: 20
26                 # 配置获取连接等待超时的时间
27                 maxWait: 60000
28                 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
29                 timeBetweenEvictionRunsMillis: 60000
30                 # 配置一个连接在池中最小生存的时间,单位是毫秒
31                 minEvictableIdleTimeMillis: 30000
32                 validationQuery: select 'x'
33                 testWhileIdle: true
34                 testOnBorrow: false
35                 testOnReturn: false
36                 # 打开PSCache,并且指定每个连接上PSCache的大小
37                 poolPreparedStatements: true
38                 maxPoolPreparedStatementPerConnectionSize: 20
39                 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
40                 filters: config,stat,slf4j
41                 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
42                 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;
43                 # 合并多个DruidDataSource的监控数据
44                 useGlobalDataSourceStat: true
45     kuta:
46         multi-tenant:
47             # 登录失败阈值
48             login-failure-threshold: 5
49             standalone-tenant-db-name-prefix: 'saas_sa_'
50             master-db-name: 'saas_master'
51             jackson:
52                 date-format: yyyy-MM-dd HH:mm:ss
53                 time-zone: GMT+8
54             wechat:
55                 third-party:
56                     enabled: true
57                     app-id: xxx
58                     app-secret: xxx
59                     message-verify-token: xxx
60                     message-decrypt-key: xxx
61                     auth-redirect-uri: https://merchant.xxx.com/#/wxAuthResult
62                     required-private-infos:
63                         - onLocationChange
64             algorithms:
65                 resource-mapping:
66                     cotenancy-tenant:
67                         type: 'COTENANCY'
68                         props:
69                             use-standalone-database: false
70                             divide-table-by-date: false
71                             file-upload-strategy: LOCAL
72                     enterprise-tenant:
73                         type: 'ENTERPRISE'
74                         props:
75                             use-standalone-database: true
76                             divide-table-by-date: false
77                             file-upload-strategy: OSS
78                     flagship-tenant:
79                         type: 'FLAGSHIP'
80                         props:
81                             use-standalone-database: true
82                             divide-table-by-date: false
83                             file-upload-strategy: OBS
84                             
85 mybatis-plus:
86     global-config:
87         banner: true
88         db-config:
89             # 已删除
90             logic-delete-value: true
91             #未删除
92             logic-not-delete-value: false
93     type-aliases-package: org.example.saas.core.pojo;com.chia.multienty.core.pojo
94     mapperLocations: classpath*:mapper/**/*.xml
95     configuration:
96         log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
View Code

 

创建master模块配置

saasdemo-master-dev.yml
spring:
    shardingSphere:
        # master不开启分片
        enabled: false
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        dynamic:
            primary: ds_master
            datasource:
                ds_master:
                    driver-class-name: com.mysql.cj.jdbc.Driver
                    url: jdbc:mysql://xxx.com:3333/xxxx?autoReconnect=true&useUnicode=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
                    username: xxxx
                    password: xxxx
                ds_root:
                    driver-class-name: com.mysql.cj.jdbc.Driver
                    url: jdbc:mysql://kutashop.cn:3333/mysql?autoReconnect=true&useUnicode=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
                    username: root
                    password: xxxx

    kuta:
        multi-tenant:
            # 开启后此应用将可提供multienty-core中提供的基础服务
            base-module-enabled: true
            domain: master.xxx.com
            security:
                auth:
                    header: X-TOKEN
                    token-prefix: ORDER
                    base64-secret: 5LmQ6IGa5oxX5piv5LiA5Liq5aW957O757uf56FK5aW957O757uf6K+95sOo5oSP5LiN6KaB5Zyo5LiK6Z2i5Y+R5biD6L+d5rOV5L+h5oGv6L+Z5qC3566h55CG5ZGY5Lmf5LiN5aW95aSE55CG55qE
                    # 令牌持有时间(秒)
                    token-holding-time: 86400
                    # 客户持有令牌时间,-1永久
                    customer-token-time: 86400
                    # 续期时长
                    renew-time: 86400
                    # 是否支持多点登陆
                    multipoint-login-enabled: true
                    ignore-paths:
                        - /file/upload
                rsa:
                    # 请根据自身情况配置
                    private-key: xxx
                    public-key: xxx==
            file:
                # 大写
                storage-mode: LOCAL
                custom:
                    custom-file-upload-service-impl-class: org.example.saas.core.strategy.file.impl.QNYFileUploadServiceImpl
                local:
                    path-prefix: C:\projects\multi-tenant\store
                    url-prefix: https://${spring.kuta.multi-tenant.domain}/local/

 

idea中创建master模块

master模块pom配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <parent>
 8         <groupId>org.example</groupId>
 9         <artifactId>SaasDemo</artifactId>
10         <version>1.0-SNAPSHOT</version>
11     </parent>
12 
13     <artifactId>saasdemo-master</artifactId>
14 
15     <properties>
16         <maven.compiler.source>8</maven.compiler.source>
17         <maven.compiler.target>8</maven.compiler.target>
18         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19     </properties>
20     <dependencies>
21         <dependency>
22             <groupId>org.example</groupId>
23             <artifactId>saasdemo-core</artifactId>
24         </dependency>
25         <dependency>
26             <groupId>com.chia</groupId>
27             <artifactId>multienty-core-mysql-resource</artifactId>
28             <version>${chia.multienty.verion}</version>
29         </dependency>
30     </dependencies>
31     <build>
32         <pluginManagement>
33             <plugins>
34                 <plugin>
35                     <groupId>org.springframework.boot</groupId>
36                     <artifactId>spring-boot-maven-plugin</artifactId>
37                     <configuration>
38                         <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
39                     </configuration>
40                 </plugin>
41             </plugins>
42         </pluginManagement>
43     </build>
44 </project>

 

创建配置和目录

注意:db.migration.master是三层目录,并非同一级目录

application.yml

spring:
  profiles:
    active: dev

 

bootstrap.yml

server:
  port: 8879

spring:
  application:
    name: saasdemo-master
  cloud:
    nacos:
      discovery:
        server-addr: nacos.xxx.com:18848
        namespace: xxxx-xxx-xxx-xxx
        username: xxxx
        password: xxxx
      config:
        server-addr: nacos.xxx.cn:18848
        namespace: xxxx-xxx-xxx-xxx
        username: xxx
        password: xxxx
        file-extension: yml
        extension-configs[0]:
          data-id: multienty.yml
          group: DEFAULT_GROUP
          refresh: true
        extension-configs[1]:
          data-id: redis.yml
          group: DEFAULT_GROUP
          refresh: true
        extension-configs[2]:
          data-id: rabbitmq.yml
          group: DEFAULT_GROUP
          refresh: true
seata:
  enabled: true
  application-id: seata-server
  # 客户端和服务端在同一个事务组; Seata 事务组编号,用于 TC 集群名, 一定要和 config.tx(nacos) 中配置的相同
  tx-service-group: tx_master_group
  # 自动数据源代理
  enable-auto-data-source-proxy: false
  # 数据源代理模式(分布式事务方案)
  data-source-proxy-mode: AT
  service:
    vgroup-mapping:
      tx_master_group: default
  config:
    # support: nacos, consul, apollo, zk, etcd3, file
    type: nacos
    nacos:
      server-addr: nacos.xxx.com:18848
      namespace: xxxx-xxx-xxx-xxxx
      group: SEATA_GROUP
      username: xxxx
      password: xxxxxx
      data-id: seata-server.properties
      cluster: default
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    nacos:
      server-addr: nacos.xxxx.cn:18848
      namespace: xxxxx-xxx-xxx-xxxx
      group: SEATA_GROUP
      username: xxxx
      password: xxxx
      # 默认TC集群名
      cluster: default
      # 服务名,与服务端中registry.conf配置要一致
      application: seata-server
      context-path:

dubbo:
  enabled: true
  metadata-report:
    address: nacos://xxxx.com:18848?username=${dubbo.metadata-report.username}&password=${dubbo.metadata-report.password}
    username: xxxx
    password: xxxxx
    parameters:
      namespace: 273e34a2-bc14-41bd-ac55-b8ab8ba27e4a
    retry-times: 30  #重试次数,默认100
    cycle-report: false #关闭定时刷新
  application:
    name: master-provider
    # 禁用QOS同一台机器可能会有端口冲突现象
    qos-enable: false
    qos-accept-foreign-ip: false
    service-discovery:
      migration: FORCE_APPLICATION # FORCE_APPLICATION,只消费应用级地址,如无地址则报错,单订阅 3.x 地址
  protocol:
    name: dubbo
    port: -1
  scan:
    base-packages: org.example.saas.master.dubbo.service.impl,com.chia.multienty.core.dubbo.service.impl
  cloud:
    subscribed-services: saasdemo-user #, kuta-order, kuta-delivery, kuta-marketing, kuta-storage

  registry:
    address: nacos://xxxx.com:xxxx?username=${dubbo.metadata-report.username}&password=${dubbo.metadata-report.password}
    parameters:
      namespace: 273e34a2-bc14-41bd-ac55-b8ab8ba27e4a
  consumer:
    check: false

 

创建springboot应用入口

@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(value = {
        "com.chia.multienty.core",
        "org.example.saas.core",
        "org.example.saas.master",
})
@EnableDubbo
@MapperScan(value={"com.chia.multienty.core.mapper","org.example.saas.core.mapper"})
public class MasterApplication {
    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(MasterApplication.class, args);

    }
}

 

posted @ 2024-02-24 23:14  kutasms  阅读(75)  评论(0)    收藏  举报