欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合ShardingSphere的示例代码

程序员文章站 2022-03-04 15:25:34
目录二、nacos数据源配置概要: shardingsphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由sharding-jdbc、sharding-proxy和sharding-si...

概要: shardingsphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由sharding-jdbc、sharding-proxy和sharding-sidecar(计划中)这3款相互独立的产品组成。 他们均提供标准化的数据分片、分布式事务和数据库治理功能,可适用于如java同构、异构语言、云原生等各种多样化的应用场景。

官网地址:

一、相关依赖

<dependency>
   <groupid>io.shardingsphere</groupid>
    <artifactid>sharding-core</artifactid>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupid>io.shardingsphere</groupid>
    <artifactid>sharding-jdbc-spring-namespace</artifactid>
    <version>3.1.0</version>
</dependency>

二、nacos数据源配置

sharding:
  datasource:
    db0:
      driverclassname: com.mysql.cj.jdbc.driver
      url: mysql://127.0.0.1:3306/demo0
      username: root
      password: 123456
    db1:
      driverclassname: com.mysql.cj.jdbc.driver
      url: mysql://127.0.0.1:3306/demo1
      username: root
      password: 123456

三、项目配置

bootstrap-dev.properties
spring:
  application:
    name: demo
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
      config:
        namespace: 9c6b8156-d045-463d-8fe6-4658ce78d0cc
        file-extension: yml

sqlsessionconfig

package com.example.demo.config;

import com.baomidou.mybatisplus.extension.plugins.paginationinterceptor;
import com.baomidou.mybatisplus.extension.spring.mybatissqlsessionfactorybean;

import org.apache.ibatis.plugin.interceptor;
import org.mybatis.spring.mapper.mapperscannerconfigurer;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.core.io.support.pathmatchingresourcepatternresolver;

import javax.sql.datasource;

@configuration
public class sqlsessionconfig {

    private logger logger = loggerfactory.getlogger(sqlsessionconfig.class);
    
    @bean("mysqlsessionfactorybean")
    public mybatissqlsessionfactorybean createsqlsessionfactory(@qualifier("datasource") datasource datasource,
                                                                @qualifier("paginationinterceptor") paginationinterceptor paginationinterceptor) {

        // mybatissqlsessionfactory
        mybatissqlsessionfactorybean sqlsessionfactorybean = null;
        try {
            // 实例sessionfactory
            sqlsessionfactorybean = new mybatissqlsessionfactorybean();
            // 配置数据源
            sqlsessionfactorybean.setdatasource(datasource);
            // 设置 mybatis-plus 分页插件
            interceptor [] plugins = {paginationinterceptor};
            sqlsessionfactorybean.setplugins(plugins);
            // 加载mybatis配置文件
            pathmatchingresourcepatternresolver resourcepatternresolver = new pathmatchingresourcepatternresolver();
            sqlsessionfactorybean.setmapperlocations(resourcepatternresolver.getresources("classpath*:mapper/*.xml"));
        } catch (exception e) {
            logger.error("创建sqlsession连接工厂错误:{}", e.getmessage());
        }
        return sqlsessionfactorybean;
    }

    @bean
    public mapperscannerconfigurer mygetmapperscannerconfigurer() {
        mapperscannerconfigurer mymapperscannerconfigurer = new mapperscannerconfigurer();
        mymapperscannerconfigurer.setbasepackage("com.example.demo.mapper");
        mymapperscannerconfigurer.setsqlsessionfactorybeanname("mysqlsessionfactorybean");
        return mymapperscannerconfigurer;
    }
}

datasourceconfig

package com.example.demo.config;

import com.alibaba.druid.pool.druiddatasource;
import io.shardingsphere.api.config.rule.shardingruleconfiguration;
import io.shardingsphere.shardingjdbc.api.shardingdatasourcefactory;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;

import javax.sql.datasource;
import java.sql.sqlexception;
import java.util.hashmap;
import java.util.map;
import java.util.properties;

@configuration
@configurationproperties(prefix = "sharding")
public class datasourceconfig  {

    private map<string, druiddatasource> datasource;

    public map<string, druiddatasource> getdatasource() {
        return datasource;
    }

    public void setdatasource(map<string, druiddatasource> datasource) {
        this.datasource = datasource;
    }

    @bean("datasource")
    public datasource getdatasource(@qualifier("shardingconfig") shardingruleconfiguration shardingruleconfig,
                                    @qualifier("properties") properties properties) throws sqlexception {

        map<string, datasource> datasourcemap = new hashmap<>();
        datasource.foreach(datasourcemap::put);
        return shardingdatasourcefactory.createdatasource(datasourcemap, shardingruleconfig, new hashmap<>(), properties);
    }


    @bean("properties")
    public properties getproperties(){
        // 获取数据源对象
        properties props=new properties();
        /*
         * ==== properties取值范围 ====
         *
         * sql_show("sql.show", string.valueof(boolean.false), boolean.type),
         * acceptor_size("acceptor.size", string.valueof(runtime.getruntime().availableprocessors() * 2), integer.type),
         * executor_size("executor.size", string.valueof(0), integer.type),
         * max_connections_size_per_query("max.connections.size.per.query", string.valueof(1), integer.type),
         * proxy_frontend_flush_threshold("proxy.frontend.flush.threshold", string.valueof(128), integer.type),
         * proxy_transaction_type("proxy.transaction.type", "local", string.class),
         * proxy_opentracing_enabled("proxy.opentracing.enabled", string.valueof(boolean.false), boolean.type),
         * proxy_backend_use_nio("proxy.backend.use.nio", string.valueof(boolean.false), boolean.type),
         * proxy_backend_max_connections("proxy.backend.max.connections", string.valueof(8), integer.type),
         * proxy_backend_connection_timeout_seconds("proxy.backend.connection.timeout.seconds", string.valueof(60), integer.type),
         * check_table_metadata_enabled("check.table.metadata.enabled", string.valueof(boolean.false), boolean.type);
         */
        props.put("sql.show", "true");
        return props;
    }
}

shardingruleconfig

package com.example.demo.config;

import io.shardingsphere.api.config.rule.shardingruleconfiguration;
import io.shardingsphere.core.yaml.sharding.yamlshardingconfiguration;
import io.shardingsphere.core.yaml.sharding.yamlshardingruleconfiguration;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.beans.factory.annotation.value;

import java.io.file;

@configuration
public class shardingruleconfig implements applicationcontextaware  {

 /* 获取环境变量 */
 @value("${spring.profiles.active}")
    private string profile;

    @bean("shardingconfig")
    public shardingruleconfiguration getshardingruleconfig() throws exception {
  
  // 获取yml路由规则配置文件
        file yamlfile = new file("src/main/resources/sharding/" + profile + "/sharding.yml");
        yamlshardingconfiguration yamlshardingruleconfiguration = yamlshardingconfiguration.unmarshal(yamlfile);
        yamlshardingruleconfiguration shardingrule = yamlshardingruleconfiguration.getshardingrule();
        if (null == shardingrule) {
            throw new exception("yamlshardingruleconfiguration is null!");
        }
        return shardingrule.getshardingruleconfiguration();
        
    }
}

src/main/resources/dev/sharding.yml

shardingrule:
  tables:
    user:
      actualdatanodes: db${0..1}.user${0..1}
      databasestrategy:
        inline:
          shardingcolumn: id
          algorithmexpression: db${id % 2}
      tablestrategy:
        inline:
          shardingcolumn: id
          algorithmexpression: user${id % 2}

注:修复相同路由字段导致部分分表无法落地数据,可以自定义相应规则,例如修改为以下配置:

shardingrule:
  tables:
    user:
      actualdatanodes: db${0..1}.user${0..1}
      databasestrategy:
        inline:
          shardingcolumn: id
          algorithmexpression: db${math.round(id / 2) % 2}
      tablestrategy:
        inline:
          shardingcolumn: id
          algorithmexpression: user${id % 2}

四、验证

2020-05-11 09:51:09.239  info 6352 --- [           main] trationdelegate$beanpostprocessorchecker : bean 'org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration' of type [org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration$$enhancerbyspringcglib$$dd8e22ae] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: spring boot ::        (v2.2.6.release)

2020-05-11 09:51:09.479  info 6352 --- [           main] c.a.c.n.c.nacospropertysourcebuilder     : loading nacos data, dataid: 'demo', group: 'default_group', data: spring:
  profiles:
    active: dev

sharding:
  datasource:
    db0:
      driverclassname: com.mysql.cj.jdbc.driver
      jdbc-url: jdbc:mysql://106.13.181.6:3306/demo0
      username: root
      password: 123456
    db1:
      driverclassname: com.mysql.cj.jdbc.driver
      jdbc-url: jdbc:mysql://106.13.181.6:3306/demo1
      username: root
      password: 123456
2020-05-11 09:51:09.489  warn 6352 --- [           main] c.a.c.n.c.nacospropertysourcebuilder     : ignore the empty nacos configuration and get it based on dataid[demo.yml] & group[default_group]
2020-05-11 09:51:09.495  warn 6352 --- [           main] c.a.c.n.c.nacospropertysourcebuilder     : ignore the empty nacos configuration and get it based on dataid[demo-dev.yml] & group[default_group]
2020-05-11 09:51:09.495  info 6352 --- [           main] b.c.propertysourcebootstrapconfiguration : located property source: compositepropertysource {name='nacos', propertysources=[nacospropertysource {name='demo-dev.yml'}, nacospropertysource {name='demo.yml'}, nacospropertysource {name='demo'}]}
2020-05-11 09:51:09.499  info 6352 --- [           main] com.example.demo.demoapplication         : the following profiles are active: dev
2020-05-11 09:51:09.965  warn 6352 --- [           main] o.m.s.mapper.classpathmapperscanner      : skipping mapperfactorybean with name 'usermapper' and 'com.example.demo.mapper.usermapper' mapperinterface. bean already defined with the same name!
2020-05-11 09:51:09.965  warn 6352 --- [           main] o.m.s.mapper.classpathmapperscanner      : no mybatis mapper was found in '[com.example.demo.mapper]' package. please check your configuration.
2020-05-11 09:51:09.966  info 6352 --- [           main] o.s.c.a.configurationclasspostprocessor  : cannot enhance @configuration bean definition 'sqlsessionconfig' since its singleton instance has been created too early. the typical cause is a non-static @bean method with a beandefinitionregistrypostprocessor return type: consider declaring such methods as 'static'.
2020-05-11 09:51:09.989  info 6352 --- [           main] o.s.cloud.context.scope.genericscope     : beanfactory id=3955a554-148e-313a-91f9-d6a10f2dc8c3
2020-05-11 09:51:10.150  info 6352 --- [           main] trationdelegate$beanpostprocessorchecker : bean 'org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration' of type [org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration$$enhancerbyspringcglib$$dd8e22ae] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying)
2020-05-11 09:51:10.380  info 6352 --- [           main] o.s.b.w.embedded.tomcat.tomcatwebserver  : tomcat initialized with port(s): 8080 (http)
2020-05-11 09:51:10.386  info 6352 --- [           main] o.a.coyote.http11.http11nioprotocol      : initializing protocolhandler ["http-nio-8080"]
2020-05-11 09:51:10.387  info 6352 --- [           main] o.apache.catalina.core.standardservice   : starting service [tomcat]
2020-05-11 09:51:10.387  info 6352 --- [           main] org.apache.catalina.core.standardengine  : starting servlet engine: [apache tomcat/9.0.33]
2020-05-11 09:51:10.507  info 6352 --- [           main] o.a.c.c.c.[tomcat].[localhost].[/]       : initializing spring embedded webapplicationcontext
2020-05-11 09:51:10.508  info 6352 --- [           main] o.s.web.context.contextloader            : root webapplicationcontext: initialization completed in 994 ms
2020-05-11 09:51:10.770  info 6352 --- [           main] com.zaxxer.hikari.hikaridatasource       : hikaripool-1 - starting...
2020-05-11 09:51:11.562  info 6352 --- [           main] com.zaxxer.hikari.hikaridatasource       : hikaripool-1 - start completed.
2020-05-11 09:51:11.570  info 6352 --- [           main] com.zaxxer.hikari.hikaridatasource       : hikaripool-2 - starting...
2020-05-11 09:51:12.226  info 6352 --- [           main] com.zaxxer.hikari.hikaridatasource       : hikaripool-2 - start completed.
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.3.1 
2020-05-11 09:51:12.876  warn 6352 --- [           main] c.n.c.sources.urlconfigurationsource     : no urls will be polled as dynamic configuration sources.
2020-05-11 09:51:12.877  info 6352 --- [           main] c.n.c.sources.urlconfigurationsource     : to enable urls as dynamic configuration sources, define system property archaius.configurationsource.additionalurls or make config.properties available on classpath.
2020-05-11 09:51:12.880  warn 6352 --- [           main] c.n.c.sources.urlconfigurationsource     : no urls will be polled as dynamic configuration sources.
2020-05-11 09:51:12.880  info 6352 --- [           main] c.n.c.sources.urlconfigurationsource     : to enable urls as dynamic configuration sources, define system property archaius.configurationsource.additionalurls or make config.properties available on classpath.
2020-05-11 09:51:13.019  info 6352 --- [           main] o.s.s.concurrent.threadpooltaskexecutor  : initializing executorservice 'applicationtaskexecutor'
2020-05-11 09:51:13.257  info 6352 --- [           main] o.s.s.c.threadpooltaskscheduler          : initializing executorservice
2020-05-11 09:51:13.477  info 6352 --- [           main] o.a.coyote.http11.http11nioprotocol      : starting protocolhandler ["http-nio-8080"]
2020-05-11 09:51:13.495  info 6352 --- [           main] o.s.b.w.embedded.tomcat.tomcatwebserver  : tomcat started on port(s): 8080 (http) with context path ''
2020-05-11 09:51:13.554  info 6352 --- [           main] c.a.c.n.registry.nacosserviceregistry    : nacos registry, default_group demo 10.118.37.75:8080 register finished
2020-05-11 09:51:13.621  info 6352 --- [           main] com.example.demo.demoapplication         : started demoapplication in 5.276 seconds (jvm running for 6.226)
2020-05-11 09:51:16.719  info 6352 --- [nio-8080-exec-2] o.a.c.c.c.[tomcat].[localhost].[/]       : initializing spring dispatcherservlet 'dispatcherservlet'
2020-05-11 09:51:16.720  info 6352 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet        : initializing servlet 'dispatcherservlet'
2020-05-11 09:51:16.730  info 6352 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet        : completed initialization in 10 ms
2020-05-11 09:51:16.792  info 6352 --- [nio-8080-exec-2] com.example.demo.config.logaspect        : 
 请求信息:
【请求地址】:/demo/create
【请求头】:content-type = application/json, user-agent = postmanruntime/7.24.0, accept = */*, postman-token = 25dbfb89-782d-45b2-bbb1-b41380c27af7, host = localhost:8080, accept-encoding = gzip, deflate, br, connection = keep-alive, content-length = 61
【请求方法】:string com.example.demo.controller.usercontroller.create(userdto)
【请求参数】:[userdto(id=123458, name=zhangsan, phone=17751033130, sex=1)]
2020-05-11 09:51:16.832 debug 6352 --- [nio-8080-exec-2] c.example.demo.mapper.usermapper.insert  : ==>  preparing: insert into user ( id, name, sex, phone, create_time, enable, version ) values ( ?, ?, ?, ?, ?, ?, ? ) 
2020-05-11 09:51:16.848 debug 6352 --- [nio-8080-exec-2] c.example.demo.mapper.usermapper.insert  : ==> parameters: 123458(long), zhangsan(string), man(string), 17751033130(string), 2020-05-11t09:51:16.797(localdatetime), true(boolean), 1(long)
2020-05-11 09:51:16.905  info 6352 --- [nio-8080-exec-2] shardingsphere-sql                       : rule type: sharding
2020-05-11 09:51:16.905  info 6352 --- [nio-8080-exec-2] shardingsphere-sql                       : logic sql: insert into user  ( id,
name,
sex,
phone,
create_time,
enable,
version )  values  ( ?,
?,
?,
?,
?,
?,
? )
2020-05-11 09:51:16.905  info 6352 --- [nio-8080-exec-2] shardingsphere-sql                       : sqlstatement: insertstatement(super=dmlstatement(super=io.shardingsphere.core.parsing.parser.sql.dml.insert.insertstatement@362afd05), columns=[column(name=id, tablename=user), column(name=name, tablename=user), column(name=sex, tablename=user), column(name=phone, tablename=user), column(name=create_time, tablename=user), column(name=enable, tablename=user), column(name=version, tablename=user)], generatedkeyconditions=[], insertvalues=insertvalues(insertvalues=[insertvalue(type=values, expression=( ?,
?,
?,
?,
?,
?,
? ), parameterscount=7)]), columnslistlastposition=71, generatekeycolumnindex=-1, insertvalueslistlastposition=105)
2020-05-11 09:51:16.905  info 6352 --- [nio-8080-exec-2] shardingsphere-sql                       : actual sql: db0 ::: insert into user0  ( id,
name,
sex,
phone,
create_time,
enable,
version )  values  ( ?,
?,
?,
?,
?,
?,
? ) ::: [[123458, zhangsan, man, 17751033130, 2020-05-11t09:51:16.797, true, 1]]
2020-05-11 09:51:17.132 debug 6352 --- [nio-8080-exec-2] c.example.demo.mapper.usermapper.insert  : <==    updates: 1
2020-05-11 09:51:17.135  info 6352 --- [nio-8080-exec-2] com.example.demo.config.logaspect        : 
 执行结果:
【响应结果】:"ok"
【执行耗时】:343毫秒

到此这篇关于springboot整合shardingsphere的示例代码的文章就介绍到这了,更多相关springboot整合shardingsphere内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!