ShardingSphere RAW JDBC 分布式事务XA 代码示例

SpringBoot整合ShardingJdbc实现XA分布式事务 SpringBoot整合ShardingJdbc实现XA分布式事务 什么是分布式事务? 关于分布式事务的介绍,请参考ShardingJdbc的介绍:分布式事务 官方文档分布式事务使用示例:使用示例,点进去之后,拉到最下面即可看到 官方example。 我这里仅做一个最简单的演示: 首先说明一下数据库相关信息 我这里使用了两个数据源,3306mysql服务和3307mysql服务,我本地起了两个mysql服务,端口号分别是3306和3307 3306mysql服务创建了数据库test,3307mysql服务 阅读详情

ShardingSphere RAW JDBC 分布式事务XA 代码示例


项目工程在:transaction-2pc-xa-raw-jdbc-example

代码简介

    基于ShardingSphere的Atomikos XA实现一个简单的分布式事务应用demo

环境配置

    启动两个MySQL5.7的docker镜像(8.0的一直报事务相关的错的,不知啥原因,换成5.7就好了),下面命令直接复制运行即可:

# 启动两个mysql
docker run --name mysql11 -p 3311:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_ROOT_HOST=% -d mysql:5.7
docker run --name mysql12 -p 3312:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_ROOT_HOST=% -d mysql:5.7

# 在11上创建数据库demo_ds_0,运行下面的SQL语句初始化数据库和表
docker exec -ti mysql11 mysql -u root -p

create database demo_ds_0;
use demo_ds_0;
CREATE TABLE IF NOT EXISTS t_order_0 (order_id BIGINT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (order_id));
CREATE TABLE IF NOT EXISTS t_order_1 (order_id BIGINT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (order_id));
    

# 在12上创建数据库demo_ds_1,运行下面的SQL语句初始化数据库和表
docker exec -ti mysql12 mysql -u root -p

create database demo_ds_1;
use demo_ds_1;
CREATE TABLE IF NOT EXISTS t_order_0 (order_id BIGINT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (order_id));
CREATE TABLE IF NOT EXISTS t_order_1 (order_id BIGINT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (order_id));

程序配置

Maven依赖

    核心依赖下面几个:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>transaction-2pc-xa-raw-jdbc-example</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId> <!-- Use 'netty-all' for 4.0 or above -->
            <version>8.0.14</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc-core</artifactId>
            <version>5.0.0-alpha</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-transaction-xa-core</artifactId>
            <version>5.0.0-alpha</version>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.2.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

shardingSphere数据库配置文件

    如上面的docker数据库配置,这里设置了两个数据库,各自有两张表

dataSources:
  ds_0: !!com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3311/demo_ds_0?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: root
    autoCommit: false
  ds_1: !!com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3312/demo_ds_1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: root
    autoCommit: false

rules:
- !SHARDING
  tables:
    t_order:
      actualDataNodes: ds_${0..1}.t_order_${0..1}
      databaseStrategy:
        standard:
          shardingColumn: user_id
          shardingAlgorithmName: database_inline
      tableStrategy:
        standard:
          shardingColumn: order_id
          shardingAlgorithmName: t_order_inline
  bindingTables:
    - t_order

  shardingAlgorithms:
    database_inline:
      type: INLINE
      props:
        algorithm-expression: ds_${user_id % 2}
    t_order_inline:
      type: INLINE
      props:
        algorithm-expression: t_order_${order_id % 2}

props:
  sql-show: true

主程序

    暴力直接的原生测试,代码如下:

package com.example.demo;

import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class Transaction2pcXaRawJdbcExampleApplication {

    /**
     * 第一次插入数据正常运行成功
     * 第二次插入数据由于主键冲突,导致回滚
     */
    public static void main(String[] args) throws IOException, SQLException {
        DataSource dataSource = getShardingDatasource();
        cleanupData(dataSource);

        TransactionTypeHolder.set(TransactionType.XA);

        Connection conn = dataSource.getConnection();
        String sql = "insert into t_order (user_id, order_id) VALUES (?, ?);";

        System.out.println("First XA Start insert data");
        try (PreparedStatement statement = conn.prepareStatement(sql)) {
            conn.setAutoCommit(false);
            for (int i = 1; i < 11; i++) {
                statement.setLong(1, i);
                statement.setLong(2, i);
                statement.executeUpdate();
            }
            conn.commit();
        }

        System.out.println("First XA insert successful");

        // 设置id+5,如果设置XA事务成功,则所有的数据都不会插入
        // 设置id+5,如果设置XA事务不成功,则id大于10的数据就会插入到数据库
        // 程序运行完毕后,查看数据库,没有id大于10的数据,所以XA设置成功
        System.out.println("Second XA Start insert data");
        try (PreparedStatement statement = conn.prepareStatement(sql)) {
            conn.setAutoCommit(false);
            for (int i = 1; i < 11; i++) {
                statement.setLong(1, i+5);
                statement.setLong(2, i+5);
                statement.executeUpdate();
            }
            conn.commit();
        } catch (Exception e) {
            System.out.println("Second XA insert failed");
            conn.rollback();
        } finally {
            conn.close();
        }
        System.out.println("Second XA insert successful");
    }

    private static void cleanupData(DataSource dataSource) {
        System.out.println("Delete all Data");
        try (Connection conn = dataSource.getConnection(); Statement statement = conn.createStatement()) {
            statement.execute("delete from t_order;");
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("Delete all Data successful");
    }

    /**
     * 生成DataSource,文件路径自行替换
     * @return
     * @throws IOException
     * @throws SQLException
     */
    static private DataSource getShardingDatasource() throws IOException, SQLException {
        String fileName = "F:\\Code\\Java\\JAVA-000\\homework\\shardingSphere-jdbc-example\\transaction-example\\transaction-2pc-xa-raw-jdbc-example\\src\\main\\resources\\sharding-databases-tables.yaml";
        File yamlFile = new File(fileName);
        return YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
    }

}
JDBC中BLOB/long raw字段的读写 一、读long raw字段byte[] bytes = SourceResultSet.getBytes("图像数据") 二、写long raw字段preparedStmt.setBinaryStream(i, new ByteArrayInputStream(bytes),size);三、读BLOB字段oracle.sql.BLOB blob = (ora 阅读详情

相关推荐

ShardingSphere与Narayana的XA分布式事务实现示例

本文将为您提供一个示例,展示如何使用ShardingSphere的RAW JDBC和Narayana的XA来实现分布式事务。在上面的示例代码中,我们首先设置事务类型为XA,然后创建了一个UserTransactionManager实例作为XA事务管理器。XA是一种用于分布式事务的协议,它允许多个资源(例如数据库)参与到一个全局事务中,并保证这些资源的一致性。使用ShardingSphere的RAW JDBC和Narayana的XA,您可以实现分布式事务的一致性和可靠性。

Byte_O_O的博客 252

ShardingSphere 升级到5.5.2适配springboot3.3.5遇到的问题汇总 (已解决)

本文介绍了ShardingSphere与Spring Boot 3.x的兼容性配置方案。主要包含以下内容:1)版本要求:ShardingSphere 5.3.0+需配合Spring Boot 3.x和JDK17+;2)依赖调整:需移除spring-boot-starter依赖,改用原生JDBC驱动;3)数据源配置:通过YAML文件和自定义DataSource Bean实现;4)分库分表规则配置示例。文中特别强调要正确处理依赖排除、YAML文件读取方式等问题,并提供了具体的pom.xml配置和Java代码实现

weixin_43100232的博客 5416

Sharding-JDBC分布式事务应用

Sharding-JDBC分布式事务应用

Apache ShardingSphere

Apache ShardingSphere 是一款分布式的数据库生态系统,可以将任意的数据库转换为分布式数据库,并通过数据分片、弹性伸缩,加密等功能对原来数据进行增强官网:https://shardingsphere.apache.org/Apache ShardingSphere 设计哲学为 Database Plus,皆在异构结构数据库上层的标准和生态。他关注如何充分合理的利用数据库的计算和存储能力,而并非实现一个全新的数据库,他站在数据库的上层角度,关注他们之间的协作多于数据库自身。

weixin_47748260的博客 2167

Codex API 直接集成指南:告别中转代理,构建稳定高效的 AI 应用

在 AI 应用开发中,API 集成是连接模型能力与业务逻辑的核心环节。其基本原理是通过 HTTP 协议,按照服务提供商定义的规范发送请求并解析响应,实现远程调用。标准化的 API 设计确保了跨平台和跨语言的互操作性,其技术价值在于提供了稳定、可控且可扩展的服务接入方式,是构建企业级智能应用的基础。在实际应用场景中,开发者常需集成如 Codex 这类聚合了多种大语言模型的平台,以调用诸如 DeepSeek 等先进模型。然而,部分开发者仍依赖过时的第三方中转代理工具,这不仅引入了单点故障和版本锁定的风险,还可能

weixin_28224217的博客 338

【零基础】手把手教你使用Docker部署Springboot项目(详细版)

还不会使用Docker部署Springboot项目的小伙伴,不妨进来看看呗,希望文中内容对你有所帮助!

fengprogrammer的博客 2万+

ShardingSphere Raw JDBC 主从示例

介绍ShardingSphere-JDBC不依赖框架的简单使用

github_35735591的博客 371

基于STM32F427的模拟SSI协议绝对式编码器位置反馈通信

基于STM32F427的模拟SSI协议绝对式编码器位置反馈通信

xeke997的博客 6063

Shardingsphere整合Narayana对XA分布式事务的支持(4)

Shardingsphere整合Narayana对XA分布式事务的支持(4)Apache ShardingSphere 是一套开源的分布式数据库中间件解决方案组成的生态圈,它由 JDBC...

ShardingSphere官微 2138

1篇1章3节:R 语言的产生与发展轨迹(更新2024/08/14)

药物的研究阶段包括靶标确定、生物学模型建立、新化学实体的发现和优化新化学实体四个关键环节。每个环节都在药物研发过程中发挥着至关重要的作用。通过科学严谨的方法和技术手段,研究人员能够在药物研发过程中不断探索和优化,从而发现和开发出具有高效、安全性的候选药物,为疾病治疗提供更多的选择和希望。

MD Code 2659

17track单号查询逆向分析

这就说明该网站很有可能存在其它检测点,而检测本地替换最大可能的就是检测了代码格式化或者代码长度。也一样,要么导致网站卡死,要么会导致网页加载异常,这里可能就难到不少人了,让我们一步一步解决。而这个站主要是检测了代码格式化,无限循环检测造成了网站卡死,经多次测试发现检测点共三处。方法中代码很长,但是经调试后发现,它其实只返回一个固定的值,这里直接写死即可。同样的,虽然看起来很长,但是跟过之后就会发现流程很简单,这里主要就是对。追加了一些值,是一条很长的语句,整理代码。,核心流程也很简单,稍微跟一下就出来了,

pyzzd的博客 1621

Sharding JDBC 实战 —— 分布式事务处理

在我们使用Sharding JDBC分库分表的时候,会带来另外一个问题,就是分布式事务问题,如下图所示。用户采购商品业务,整个业务包含3个微服务: 库存服务: 扣减给定商品的库存数量。 订单服务: 根据采购请求生成订单。 账户服务: 用户账户金额扣减。 这三个业务操作应该属于同一个事务,但是这些数据却分配在不同的数据库上,所以没办法采用数据库的事务来保证数据一致性。 这个时候,要解决分布式事务问题,就需要引入全局事务。 1. 什么是全局事务呢? 全局事务是一个DTP模型的事务,所谓DTP模

Java是世界上最好的语言 6734

反光柱定位算法中的移动机器人姿态计算原理-经典三边定位最小二乘法计算定位-直接法计算定位

(二)计算姿态方式是我们已经通过最小二乘得到了小车在地图中的位置或者是雷达在地图中的位置,又因为我们知道雷达与小车的安装坐标,所以可以求解出一其中一个坐标的知量,通过小车在地图中坐标与雷达在地图中坐标可以得到一条向量,通过计算向量在地图中的角度就能得到姿态了。与最小二乘三边测量法相比,新算法在动态调整、优化过程和鲁棒性方面优势明显,尤其适合动态环境下的机器人定位,而最小二乘三边测量法在动态复杂环境中精度相对较低。(一)与(二)的区别主要是在计算姿态上的算法不同。经典三边定位最小二乘法 (法一)

苏凯的博客 1139

ShardingSphere RAW JDBC 分布式事务 Narayana XA 代码示例

基于ShardingSphere的 Narayana XA实现一个简单的分布式事务应用demo

github_35735591的博客 253

NPU性能榨取手把手教程:RK3588上YOLOv5s多线程部署与120FPS极限探索

RK3588 YOLOv5s多线程部署优化指南 本教程深入解析RK3588芯片上YOLOv5s模型的高性能多线程部署方案。RK3588作为瑞芯微旗舰AIoT芯片,内置三核NPU(6TOPS算力)和硬件加速器(RGA/VPU),为AI推理提供强大支持。通过线程池技术,我们将视频处理的读取、推理、后处理等环节解耦并行,显著提升系统吞吐量。教程详细介绍了从PyTorch到RKNN格式的模型转换流程、INT8量化方法,以及基于RKNN C++ SDK的YOLOv5推理核心实现,帮助开发者最大化发挥RK3588的AI

LXY_LOVE36的博客 973

手把手教你学Simulink——电机电磁兼容与可靠性场景示例:基于Simulink的电机噪声抑制控制仿真

本文带你完成了电机噪声抑制控制的Simulink仿真,实现了:✅ 揭示了电磁噪声从电流到声音的传递机理✅ 搭建了含死区、固定载波等噪声源的高保真模型随机PWM(消除啸叫)谐振控制器(抑制5/7次嗡鸣)谐波注入(降低THD) ✅ 通过综合方案将噪声降低10 dB以上(感知响度减半!) ✅ 为产品静音品质提升提供可落地的控制方案。

MHD0815的博客 94

数据库表是不是锁住了_Java技术分享:一致性更强的分布式数据库中间件

分布式数据库中间件 ShardingSphere 将 Sea t a 分布式事务能力进行整合,旨在打造一致性更强的分布式 数据库中间件 。背景数据库领域,分布式事务的实现主要包含:两阶段的 XA 和 BASE 柔性事务。XA 事务底层,依赖于具体的数据库厂商对 XA 两阶段提交协议的支持。 通常,XA 协议通过在 Prepare 和 Commit 阶段进行 2PL(2 阶段锁),保证了分布式事务...

weixin_42298093的博客 109

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

一致 先验分布 后验分布_ShardingSphere x Seata,一致性更强的分布式数据库中间件...

日前,分布式数据库中间件ShardingSphere将 Seata 分布式事务能力进行整合,旨在打造一致性更强的分布式数据库中间件。背景数据库领域,分布式事务的实现主要包含:两阶段的 XA 和 BASE 柔性事务。XA 事务底层,依赖于具体的数据库厂商对 XA 两阶段提交协议的支持。通常,XA 协议通过在 Prepare 和 Commit 阶段进行 2PL(2 阶段锁),保证了分布式...

weixin_33156085的博客 162

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ShardingSphere之Sharding-JDBC整合XA模式、Saga模式、Seata原理介绍以及代码演示

ShardingSphere之Sharding-JDBC整合XA模式、Saga模式、Seata原理介绍以及代码演示

weixin_44795847的博客 2595

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

ShardingSphere分库分表5-ShardingSphere的分布式事务详解

文章目录一、ShardingJDBC分布式事务快速上手LOCAL本地事务XA事务快速上手BASE柔性事务快速上手二、分布式事务原理详解XA事务Base柔性事务ShardingJDBC扩展分布式事务管理器三、ShardingProxy分布式事务示例 一、ShardingJDBC分布式事务快速上手 ShardingJDBC支持的分布式事务方式有三种 LOCAL, XA , BASE,这三种事务实现方式都是采用的对代码无侵入的方式实现的。具体见 TransactionTypeHolder.set(Transact

roykingw的专栏 2312

ShardingSphere-JDBC入门实战

http://www.manongjc.com/detail/23-ucugqdghzuagktz.html 前言 Apache ShardingSphere 是一套开源的分布式数据库解决方案组成的生态圈,它由 JDBC、Proxy 和 Sidecar(规划中)这 3 款既能够独立部署,又支持混合部署配合使用的产品组成;接下来的几篇文章将重点分析ShardingSphere-JDBC,从数据分片,分布式主键,分布式事务,读写分离,弹性伸缩等几个方面来介绍。 简介 ShardingSphere

yygr的博客 1226

Apache ShardingSphere数据脱敏全解决方案详解

Apache ShardingSphere数据脱敏全解决方案详解 作者简介 潘娟,京东数科高级DBA,主要负责京东数科数据库中间件开发、数据库运维自动化平台开发、生产数据库运维工作。多次参与京东6.18、11.11等大促活动的护航工作。曾负责京东数科数据库自动化平台设计与开发项目,现专注于A...

chuzhan7675的博客 1905

Apache ShardingSphere数据脱敏全解决方案详解(下)

点击「京东数科技术说」可快速关注「摘要」《ApacheShardingSphere数据脱敏全解决方案详解(上)》主要介绍了ShardingSphere内部脱敏功能的具体实现。本次分享承...

JDDTechTalk的博客 505

【分布式】分布式事务

一、CAP理论 CAP是 Consistency、Availability、Partition tolerance三个词语的缩写,分别表示一致性、可用性、分区容忍性。 C - Consistency 一致性是指写操作后的读操作可以读取到最新的数据状态,当数据分布在多个节点上,从任意结点读取到的数据都 是最新的状态。 如何实现一致性? 1、写入主数据库后要将数据同步到从数据库。 2、写入主数据库后,在向从数据库同步期间要将从数据库锁定,待同步完成后再释放锁,以免在新数据写入成功 后,向从数据库查询到旧的数据。

隐市高手 480

JDBC读取Oracle LONG RAW类型字段

Java代码如下: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; imp

restraint的专栏 7883
上一篇: ShardingSphere-Proxy 主从读写 入门使用
下一篇: ShardingSphere RAW JDBC 分布式事务 Narayana XA 代码示例
_萧_
博客等级 码龄10年 55粉丝 157原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值