ballerina 学习十八 事务编程
事务在分布式开发,以及微服务开发中是比较重要的
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 学习十八 事务编程的更多相关文章
- ballerina 学习十九 安全编程
ballerina 内部提供了几种常用的安全开发模型,token 认证(jwt) basic auth jwt 安全 参考代码 import ballerina/http; http:AuthPr ...
- WCF学习笔记之事务编程
WCF学习笔记之事务编程 一:WCF事务设置 事务提供一种机制将一个活动涉及的所有操作纳入到一个不可分割的执行单元: WCF通过System.ServiceModel.TransactionFlowA ...
- javaweb学习总结(三十八)——事务
一.事务的概念 事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功. 例如:A——B转帐,对应于如下两条sql语句 update from account set mone ...
- Python学习札记(三十八) 面向对象编程 Object Oriented Program 9
参考:多重继承 NOTE #!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name ...
- 强化学习(十八) 基于模拟的搜索与蒙特卡罗树搜索(MCTS)
在强化学习(十七) 基于模型的强化学习与Dyna算法框架中,我们讨论基于模型的强化学习方法的基本思路,以及集合基于模型与不基于模型的强化学习框架Dyna.本文我们讨论另一种非常流行的集合基于模型与不基 ...
- spring学习 十八 spring的声明事物
1.编程式事务: 1.1 由程序员编程事务控制代码.commit与rollback都需要程序员决定在哪里调用,例如jdbc中conn.setAutoCimmit(false),conn.commit( ...
- Scala学习十八——高级类型
一.本章要点 单例类型可用于方法串接和带对象参数的方法 类型投影对所有外部类的对象都包含了其他内部类的实例 类型别名给类型指定一个短小的名称 结构类型等效于”鸭子类型“ 存在类型为泛型的通配参数提供了 ...
- Java编程思想学习(十六) 并发编程
线程是进程中一个任务控制流序列,由于进程的创建和销毁需要销毁大量的资源,而多个线程之间可以共享进程数据,因此多线程是并发编程的基础. 多核心CPU可以真正实现多个任务并行执行,单核心CPU程序其实不是 ...
- Storm系列(十八)事务介绍
功能:将多个tuple组合成为一个批次,并保障每个批次的tuple被且仅被处理一次. storm事务处理中,把一个批次的tuple的处理分为两个阶段processing和commit阶段. proce ...
随机推荐
- zw版【转发·台湾nvp系列Delphi例程】HALCON SetWindowExtent
zw版[转发·台湾nvp系列Delphi例程]HALCON SetWindowExtent unit Unit1;interfaceuses Windows, Messages, SysUtils, ...
- Digital Image Processing 学习笔记1
第一章 1.1 数字图像 一幅图像可以定义为一个而为函数, 其中x和y是空间坐标,而在任何一对空间坐标(x, y)处的幅值f称为图像在该点处的强度或灰度.当x, y和灰度值f是有限的离散数值时,该图像 ...
- Fms3和Flex打造在线多人视频会议和视频聊天(附原代码)
Flex,Fms3系列文章导航 Flex,Fms3相关文章索引 本篇是视频聊天,会议开发实例系列文章的第3篇,该系列所有文章链接如下: http://www.cnblogs.com/aierong/a ...
- Python笔记 #05# Package & pip3
datacamp + 日常收集 How to install Package pip3 & What is difference between pip and pip3? Import P ...
- FromBottomToTop第十三周项目博客
FromBottomToTop第十三周项目博客 本周项目计划 完成游戏核心算法以及界面相关类和怪物类 项目进展 用户可选择游戏模式,共有20张不同的地图. 炮台的建立和升级. 小怪的路径算法. 参考资 ...
- HDU 2222 Keywords Search(AC自动机)题解
题意:给你几个keywords,再给你一段文章,问你keywords出现了几次. 思路:这里就要用到多模匹配算法AC自动机了,AC自动机需要KMP和字典树的知识,匹配时是在字典树上,失配我们就要用到类 ...
- 【yum】yum的使用
Yum官网 Yum的缓存 Yum仓库 Yum命令 Yum插件 yum的缓存 通过缓存可以提升我们环境的搭建效率,直接把原来缓存好的安装包数据放到新环境,省去了几个G的下载,甚至,有些时候客户现场不能联 ...
- 关于JS和JSON
讲得不准确! 看网课,JS也算是面向对象的一门语言,不过其是解释性的脚本语言. JSON是把用JS的表示法将数据包装起来进行传递用的. JS语法是松散型的,没有int String这些像JAVA里的类 ...
- POJ 3468 A Simple Problem with Integers(线段树:区间更新)
http://poj.org/problem?id=3468 题意: 给出一串数,每次在一个区间内增加c,查询[a,b]时输出a.b之间的总和. 思路: 总结一下懒惰标记的用法吧. 比如要对一个区间范 ...
- POJ 1833 排序
http://poj.org/problem?id=1833 题意: 给出一个排序,求出它之后的第k个排序. 思路: 排序原理: 1.如果全部为逆序时,说明已经全部排完了,此时回到1~n的排序. 2. ...