事务在分布式开发,以及微服务开发中是比较重要的

ballerina 支持 本地事务、xa 事务、分布式事务 ,但是具体的服务实现起来需要按照ballerian 的事务模型 infection agreement

基本事务使用(本地事务)

  • 参考代码(数据库)
import ballerina/mysql;
import ballerina/io;
endpoint mysql:Client testDB {
host: "localhost",
port: 3306,
name: "testdb",
username: "root",
password: "root",
poolOptions: { maximumPoolSize: 5 }
};function main(string... args) {
var ret = testDB->update("CREATE TABLE CUSTOMER (ID INT, NAME
VARCHAR(30))");
handleUpdate(ret, "Create CUSTOMER table"); ret = testDB->update("CREATE TABLE SALARY (ID INT, MON_SALARY FLOAT)");
handleUpdate(ret, "Create SALARY table");
transaction with retries = 4, oncommit = onCommitFunction,
onabort = onAbortFunction {
var result = testDB->update("INSERT INTO CUSTOMER(ID,NAME)
VALUES (1, 'Anne')");
result = testDB->update("INSERT INTO SALARY (ID, MON_SALARY)
VALUES (1, 2500)");
match result {
int c => {
io:println("Inserted count: " + c);
if (c == 0) {
abort;
}
}
error err => {
retry;
}
}
} onretry {
io:println("Retrying transaction");
}
ret = testDB->update("DROP TABLE CUSTOMER");
handleUpdate(ret, "Drop table CUSTOMER"); ret = testDB->update("DROP TABLE SALARY");
handleUpdate(ret, "Drop table SALARY");
testDB.stop();
}
function onCommitFunction(string transactionId) {
io:println("Transaction: " + transactionId + " committed");
}
function onAbortFunction(string transactionId) {
io:println("Transaction: " + transactionId + " aborted");
}
function handleUpdate(int|error returned, string message) {
match returned {
int retInt => io:println(message + " status: " + retInt);
error err => io:println(message + " failed: " + err.message);
}
}

分布式事务

import ballerina/math;
import ballerina/http;
import ballerina/log;
import ballerina/transactions;
@http:ServiceConfig {
basePath: "/"
}
service<http:Service> InitiatorService bind { port: 8080 } { @http:ResourceConfig {
methods: ["GET"],
path: "/"
}
init(endpoint conn, http:Request req) {
http:Response res = new;
log:printInfo("Initiating transaction...");
transaction with oncommit = printCommit,
onabort = printAbort {
log:printInfo("Started transaction: " +
transactions:getCurrentTransactionId());
boolean successful = callBusinessService();
if (successful) {
res.statusCode = http:OK_200;
} else {
res.statusCode = http:INTERNAL_SERVER_ERROR_500;
abort;
}
} var result = conn->respond(res);
match result {
error e =>
log:printError("Could not send response back to client", err = e);
() =>
log:printInfo("Sent response back to client");
}
}
}
function printAbort(string transactionId) {
log:printInfo("Initiated transaction: " + transactionId + " aborted");
}
function printCommit(string transactionId) {
log:printInfo("Initiated transaction: " + transactionId + " committed");
}function callBusinessService() returns boolean {
endpoint http:Client participantEP {
url: "http://localhost:8889/stockquote/update"
}; boolean successful; float price = math:randomInRange(200, 250) + math:random();
json bizReq = { symbol: "GOOG", price: price };
http:Request req = new;
req.setJsonPayload(bizReq);
var result = participantEP->post("", request = req);
log:printInfo("Got response from bizservice");
match result {
http:Response res => {
successful = (res.statusCode == http:OK_200) ? true : false;
}
error => successful = false;
}
return successful;
} import ballerina/log;
import ballerina/io;
import ballerina/http;
import ballerina/transactions;
@http:ServiceConfig {
basePath: "/stockquote"
}
service<http:Service> ParticipantService bind { port: 8889 } { @http:ResourceConfig {
path: "/update"
}
updateStockQuote(endpoint conn, http:Request req) {
log:printInfo("Received update stockquote request");
http:Response res = new;
transaction with oncommit = printParticipantCommit,
onabort = printParticipantAbort { log:printInfo("Joined transaction: " +
transactions:getCurrentTransactionId()); var updateReq = untaint req.getJsonPayload();
match updateReq {
json updateReqJson => {
string msg =
io:sprintf("Update stock quote request received.
symbol:%j, price:%j",
updateReqJson.symbol,
updateReqJson.price);
log:printInfo(msg); json jsonRes = { "message": "updating stock" };
res.statusCode = http:OK_200;
res.setJsonPayload(jsonRes);
}
error e => {
res.statusCode = http:INTERNAL_SERVER_ERROR_500;
res.setPayload(e.message);
log:printError("Payload error occurred!", err = e);
}
} var result = conn->respond(res);
match result {
error e =>
log:printError("Could not send response back to initiator",
err = e);
() =>
log:printInfo("Sent response back to initiator");
}
}
}
}
function printParticipantAbort(string transactionId) {
log:printInfo("Participated transaction: " + transactionId + " aborted");
}
function printParticipantCommit(string transactionId) {
log:printInfo("Participated transaction: " + transactionId + " committed");
}

参考资料

https://ballerina.io/learn/by-example/transactions-distributed.html
https://ballerina.io/learn/by-example/local-transactions.html

 
 
 
 

ballerina 学习十八 事务编程的更多相关文章

  1. ballerina 学习十九 安全编程

      ballerina 内部提供了几种常用的安全开发模型,token 认证(jwt) basic auth jwt 安全 参考代码 import ballerina/http; http:AuthPr ...

  2. WCF学习笔记之事务编程

    WCF学习笔记之事务编程 一:WCF事务设置 事务提供一种机制将一个活动涉及的所有操作纳入到一个不可分割的执行单元: WCF通过System.ServiceModel.TransactionFlowA ...

  3. javaweb学习总结(三十八)——事务

    一.事务的概念 事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功. 例如:A——B转帐,对应于如下两条sql语句  update from account set mone ...

  4. Python学习札记(三十八) 面向对象编程 Object Oriented Program 9

    参考:多重继承 NOTE #!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name ...

  5. 强化学习(十八) 基于模拟的搜索与蒙特卡罗树搜索(MCTS)

    在强化学习(十七) 基于模型的强化学习与Dyna算法框架中,我们讨论基于模型的强化学习方法的基本思路,以及集合基于模型与不基于模型的强化学习框架Dyna.本文我们讨论另一种非常流行的集合基于模型与不基 ...

  6. spring学习 十八 spring的声明事物

    1.编程式事务: 1.1 由程序员编程事务控制代码.commit与rollback都需要程序员决定在哪里调用,例如jdbc中conn.setAutoCimmit(false),conn.commit( ...

  7. Scala学习十八——高级类型

    一.本章要点 单例类型可用于方法串接和带对象参数的方法 类型投影对所有外部类的对象都包含了其他内部类的实例 类型别名给类型指定一个短小的名称 结构类型等效于”鸭子类型“ 存在类型为泛型的通配参数提供了 ...

  8. Java编程思想学习(十六) 并发编程

    线程是进程中一个任务控制流序列,由于进程的创建和销毁需要销毁大量的资源,而多个线程之间可以共享进程数据,因此多线程是并发编程的基础. 多核心CPU可以真正实现多个任务并行执行,单核心CPU程序其实不是 ...

  9. Storm系列(十八)事务介绍

    功能:将多个tuple组合成为一个批次,并保障每个批次的tuple被且仅被处理一次. storm事务处理中,把一个批次的tuple的处理分为两个阶段processing和commit阶段. proce ...

随机推荐

  1. HDU——2955 Robberies (0-1背包)

    题意:有N个银行,每抢一个银行,可以获得\(v_i\)的前,但是会有\(p_i\)的概率被抓.现在要把被抓概率控制在\(P\)之下,求最多能抢到多少钱. 分析:0-1背包的变形,把重量变成了概率,因为 ...

  2. flask jinja的宏

    form中关于表单的定义 class AreaListForm(Form): area1 = BooleanField(u'1区', default=False) area2 = BooleanFie ...

  3. 免费美女视频聊天,多人视频会议功能加强版本(Fms3和Flex开发(附源码))

    Flex,Fms3系列文章导航 Flex,Fms3相关文章索引 本篇是视频聊天,会议开发实例系列文章的第4篇,该系列所有文章链接如下: http://www.cnblogs.com/aierong/a ...

  4. HTTP从入门到入土(4)——URI、URL和URN

    URI URI全称:Uniform Resource Identifier,中文名为统一资源标识符.用来标识唯一标识互联网上的信息资源. Web上可用的所有资源,比如html.图像.视频等,都是由UR ...

  5. 上传jar包至nexus

    上传命令: mvn deploy:deploy-file -DgroupId=com.xxx -DartifactId=xxx-pdf -Dversion=16.10.0 -Dpackaging=ja ...

  6. InstallShieldPro 2015中Basic MSI工程类型如何调用InstallScript脚本

    转载:http://blog.csdn.net/mengzhishen/article/details/8953901 这是一个Basic MSI基础知识. A. 首先在Installation De ...

  7. 【bzoj5170】Fable(树状数组)

    题目传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=5170 我们会发现,经过一轮冒泡后,若a[i]的前面有比它大的数,就一定会有一个被丢到后 ...

  8. Markdown中的表格

    参考:在简书上用Markdown写表格 | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | r ...

  9. CSS再学习 之背景色 背景图片

    背景色 p {background-color: gray;} 如果您希望背景色从元素中的文本向外少有延伸,只需增加一些内边距. p {background-color: gray; padding: ...

  10. JavaScript权威指南--Javascript子集和扩展

    知识要点 本章讨论javascript的子集和超集,其中子集的定义大部分处于安全考虑.只有使用这门语言的一个安全的子集编写脚本,才能让代码执行的更安全.更稳定.比如如何更安全地执行一段由不可信第三方提 ...