cobol 教程_现代COBOL:微服务教程

cobol 教程

You will learn and implement a microservice in COBOL without Mainframe. You will structure the project, manage dependencies, implement automatic tests and build virtualized execution environment. Finally, you will publish the microservice on GitHub under Continuous Integration workflow.

您将在没有大型机的情况下在COBOL中学习和实现微服务。 您将构建项目,管理依赖关系,实施自动测试并构建虚拟化的执行环境。 最后,您将在持续集成工作流下在GitHub上发布微服务。

前提条件 (Preconditions)

You have learned basic principles, methods and standards of COBOL. In this tutorial we’ll use GnuCOBOL — a free COBOL compiler which implements a substantial part of the COBOL 85, COBOL 2002 and COBOL 2014 standards and X/Open COBOL, as well as many extensions included in other COBOL compilers.

您已经学习了COBOL的基本原理,方法和标准。 在本教程中,我们将使用GnuCOBOL —一个免费的COBOL编译器,该编译器实现了COBOL 85,COBOL 2002和COBOL 2014标准以及X / Open COBOL的大部分内容,以及其他COBOL编译器中包括的许多扩展。

You are familiar with HTTP protocol — request and response formats.

您熟悉HTTP协议 -请求和响应格式。

You have Docker, a command-line virtualization tool, installed.

您已经安装了Docker (一种命令行虚拟化工具)。

You have NPM, a package manager for JavaScript programming language, installed.

您已经安装了NPM ,它是JavaScript编程语言的软件包管理器。

You have Git, an open source distributed version control client, installed.

您已经安装了Git (一个开源的分布式版本控制客户端)。

You have GitHub account for publishing of the microservice.

您具有用于发布微服务的GitHub帐户。

You may use any text editor you like, but I recommend Visual Studio Code (or its open-source version VSCodium) with COBOL-syntax extension bitlang.cobol installed.

您可以使用任何喜欢的文本编辑器,但是我建议安装Visual Studio Code (或其开放源代码VSCodium )并安装COBOL语法扩展名bitlang.cobol

TLDR (TLDR)

Complete source-code of this tutorial you can see on GitHub.

您可以在GitHub上看到本教程的完整源代码。

技术指标 (Specifications)

One of strengths of COBOL is a decimal mathematics. In this tutorial we’ll create a high-precision currency exchange microservice that exposes HTTP API and returns EUR amount in JSON format.

十进制数学是COBOL的强项之一。 在本教程中,我们将创建一个高精度的货币兑换微服务,该服务公开HTTP API并以JSON格式返回EUR金额。

Let’s say, the microservice awaits HTTP request GET /currency/amount on port 8000 and respond JSON {"amount": amount}, where

假设微服务在端口8000上等待HTTP请求GET / currency / amount并响应JSON {“ amount”:amount} ,其中

  • currency is a tree-letter ISO currency code, i.e. USD

    currency是一个树状字母的ISO货币代码,即USD

  • amount is a numeric value separated by dot, i.e. 999.999

    amount是一个用点分隔的数值,即999.999

Any mismatching requests, unsupported currencies, as well as calculation errors will result in 404 Not Found responses.

任何不匹配的请求,不受支持的货币以及计算错误都将导致404 Not Found响应。

Exchange rates are Euro foreign exchange reference rates published by the European Central Bank. Daily renewals of the exchange rates and multi-threading are out of scope in this tutorial.

汇率是欧洲中央银行发布的欧元外汇参考汇率。 汇率和多线程的每日续订不在本教程的讨论范围之内。

结构体 (Structure)

We need 3 directories — src for main program, tests for test program and resources for static files. Please download CSV (.zip) from ECB website and extract to resources directory. The file contains exchange rates to Euro for 32 currencies. As defined in the specification, we’ll keep the rates static.

我们需要3个目录-主程序为src测试程序为测试,静态文件为资源 。 请从ECB网站下载CSV(.zip) ,然后提取到资源目录。 该文件包含32种货币对欧元的汇率。 按照规范中的定义,我们将保持速率不变。

$ ls
resources  src  tests
$ ls resources
eurofxref.csv

Finally, please create empty microservice.cbl and microservice-test.cbl files in src and tests directories respectively. We will need them later.

最后,请分别创建SRCmicroservice.cbl微服务,test.cbl文件和测试目录。 我们稍后将需要它们。

依存关系 (Dependencies)

Our microservice depends on HTTP server for handling requests, ECB parser for CSV and GCBLUnit testing framework. All these components are available on COBOL Package Registry — cobolget.com. We can simply integrate these dependencies by using an open-source COBOL package management tool — cobolget. Here’s complete listing:

我们的微服务依赖于HTTP服务器来处理请求,用于CSV的ECB解析器GCBLUnit测试框架。 所有这些组件都可以在COBOL软件包注册表— cobolget.com上获得 。 我们可以使用开源COBOL软件包管理工具cobolget来简单地集成这些依赖 。 这是完整的清单:

$ npm install -g cobolget
$ cobolget init
Manifest modules.json created.
$ cobolget add core-network
Dependency 'core-network' has been added to the manifest.
$ cobolget add core-string
Dependency 'core-string' has been added to the manifest.
$ cobolget add --debug gcblunit
Debug dependency 'gcblunit' has been added to the manifest.
$ cobolget update
Lockfile modules-lock.json updated.
$ cobolget -t bca12d6c4efed0627c87f2e576b72bdb5ab88e34 install

We use Team Token in the last command because core-network is private package owned by Cobolget but freely shared with the community. You will see long installation log which ends with

我们在最后一个命令中使用Team Token,因为核心网络Cobolget拥有的私有软件包,但可以与社区自由共享。 您将看到以以下结尾的长安装日志

Copybook modules.cpy updated

This file, already known as COBOL Copybook, includes all direct and inherited dependencies for the microservice. We’ll use it inside our program in the next step.

该文件已被称为COBOL Copybook ,包括微服务的所有直接和继承的依赖关系。 下一步,我们将在程序中使用它。

程序 (Program)

Basically, our program must

基本上,我们的程序必须

  • read CSV file

    读取CSV文件
  • convert CSV text into the list of Currency-Rate pairs

    将CSV文本转换为货币汇率对列表
  • launch local TCP/IP server on port 8000 by

    通过以下方式在端口8000上启动本地TCP / IP服务器
  • implementing a callback which handles HTTP requests

    实现处理HTTP请求的回调
identification division.
program-id. microservice.
...
procedure division.
  *> read CSV file into csv-content
  open input file-csv.
  if not file-exists
    display "Error reading file" upon syserr
  stop run
  end-if.
  perform until exit
    read file-csv at end exit perform end-read
  end-perform.
  close file-csv.  *> convert csv-content to the list of key-value pairs
  move csv-ecb-rates(csv-content) to dataset.*> start HTTP server with http-handler callback
  call "receive-tcp" using "localhost", 8000, 0, address of entry "http-handler".
end program microservice.identification division.
program-id. http-handler.
...
procedure division using l-buffer, l-length returning omitted.
  *> initialize exchange rates
  set address of exchange-rates to dataset-ptr.

  *> parse request as "GET /<currency>/<amount>"
  unstring l-buffer(1:l-length) delimited by all SPACES into request-method, request-path.  if not http-get
    perform response-NOK
  end-if.  *> find currency and calculate eur-amount
  perform varying idx from 1 by 1 until idx > 64
  if rate-currency(idx) = get-currency
    compute eur-amount = numval(get-amount) / rate-value(idx)
      on size error perform response-NOK
    end-compute
    perform response-OK
  end-if
  end-perform.  *> or nothing
  perform response-NOK.response-OK section.
  move HTTP-OK to response-status.
  move byte-length(response-content) to response-content-length.
  perform response-any.response-NOK section.
  move HTTP-NOT-FOUND to response-status.
  move 0 to response-content-length.
  perform response-any.response-any section.
  move 1 to l-length.
  string response delimited by size into l-buffer with pointer l-length.
  subtract 1 from l-length.
  goback.
end program http-handler.copy "modules/modules.cpy".

The receive-tcp program is a server which accepts incoming connections, reads the content of the request into the buffer and shares the buffer with the callback program. The callback parses the content and replaces the buffer with a response. The server sends the response back to the client. Full listing of the program you can find on GitHub.

receive-tcp程序是一个服务器,它接受传入的连接,将请求的内容读入缓冲区,并与回调程序共享缓冲区。 回调解析内容,并用响应替换缓冲区。 服务器将响应发送回客户端。 您可以在GitHub上找到该程序的完整列表。

Let’s install GnuCOBOL Docker execution environment.

让我们安装GnuCOBOL Docker执行环境。

$ docker run -d -i --name gnucobol olegkunitsyn/gnucobol:2.2
$ docker exec -i gnucobol cobc -V
cobc (GnuCOBOL) 2.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Keisuke Nishida, Roger While, Ron Norman, Simon Sobisch, Edward Hart
Built     Jul 26 2020 07:44:23
Packaged  Sep 06 2017 18:45:29 UTC
C version "9.3.0"

In this tutorial we’ll use GnuCOBOL 2.2, only stable GnuCOBOL compiler available in the binary distributions at the moment. You may find and install it natively on your machine, too.

在本教程中,我们将使用GnuCOBOL 2.2,目前只有二进制发行版中可用的稳定GnuCOBOL编译器。 您也可以在计算机上本地找到并安装它。

测试 (Test)

Our microservice will follow Continuous Integration practices, when the developers integrate source-code into the shared repository, where each integration is getting tested automatically. For testing we’ll use simple GCBLUnit testing framework which was already installed as a debug-dependency earlier.

当开发人员将源代码集成到共享存储库中时,我们的微服务将遵循持续集成实践,其中每个集成都将自动得到测试。 对于测试,我们将使用简单的GCBLUnit测试框架,该框架先前已作为调试依赖性安装。

Let’s create Dockerfile of the microservice:

让我们创建微服务的Dockerfile

FROM olegkunitsyn/gnucobol:2.2
RUN mkdir /microservice
WORKDIR /microservice
COPY . .
EXPOSE 8000
RUN cobc -x -debug modules/gcblunit/gcblunit.cbl tests/* --job='microservice-test'

We expose port 8000 and execute microservice-test job upon each build of the image. The last element of the whole picture is a test-file microservice-test.cbl:

我们公开端口8000,并在每次构建映像时执行微服务测试作业。 整个图片的最后一个元素是一个测试文件microservice-test.cbl

>>SOURCE FORMAT FREE
identification division.
program-id. microservice-test.
environment division.
configuration section.
repository.
  function csv-ecb-rates
  function substr-pos
  function all intrinsic.
data division.
working-storage section.
  01 dataset external.
  05 dataset-ptr usage pointer.
  01 buffer pic x(1024) value "GET /USD/1 HTTP1.1".
procedure division.
  move csv-ecb-rates(concatenate("Date, USD, " x"0a" "17 July 2020, 1.1428, ")) to dataset.
  call "http-handler" using buffer, byte-length(buffer).
  perform http-handler-test.
  goback.http-handler-test section.
  call "assert-notequals" using 0, substr-pos(buffer, "HTTP/1.1 200 OK").
  call "assert-notequals" using 0, substr-pos(buffer, "Content-Type: application/json").
  call "assert-notequals" using 0, substr-pos(buffer, "Content-Length: 44").
  call "assert-equals" using 104, substr-pos(buffer, "0.8750437521876093").
end program microservice-test.copy "src/microservice.cbl".

For testing purposes I’ve prepared minimal CSV content with one single currency USD. As you can see in definition of the buffer, the test requests the conversion of 1 USD. We expect non-nullable HTTP headers, as well as high-precision exchanged amount 0.8750437521876093. The last line includes the main program we test to.

为了进行测试,我准备了最少的CSV内容(一种货币USD) 。 如您所见,在缓冲区的定义中,测试请求转换1 USD 。 我们期望不可为空的HTTP标头,以及高精度的交换量0.8750437521876093 。 最后一行包括我们要测试的主程序。

容器 (Container)

Let’s create Docker image:

让我们创建Docker映像:

$ docker build --tag microservice .
...
OK
Tests: 0000000001, Skipped: 0000000000
Assertions: 0000000004, Failures: 0000000000, Exceptions: 0000000000
...

Well done! Our Docker image successfully passed the test by evaluating 4 assertions and ready for launch.

做得好! 我们的Docker映像通过评估4个断言并成功启动而成功通过了测试。

$ docker run -d -i --name microservice -p 8000:8000 microservice
$ docker exec -i microservice cobc -j -x src/microservice.cbl
TCP server started on localhost:08000. Hit Ctrl+C to stop.

Open http://localhost:8000/USD/99.99 and http://localhost:8000/ABC/1 in the browser and see what happens. To stop and remove the container, run

在浏览器中打开http:// localhost:8000 / USD / 99.99http:// localhost:8000 / ABC / 1 ,看看会发生什么。 要停止并卸下容器,请运行

$ docker rm --force microservice

的GitHub (GitHub)

At last, we’ll publish the microservice enabling GitHub Actions workflow, where each pull request or push to the repository triggers an execution of microservice-test. All you need is docker-image.yml file in .github/workflows directory:

最后,我们将发布启用GitHub Actions的微服务,其中每个请求请求或向存储库的推送都会触发微服务测试的执行。 您需要的是.github / workflows目录中的docker -image.yml文件:

name: Docker Image CIon:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag my-image-name:$(date +%s)

结论 (Conclusion)

You have implemented the microservice by using Git libraries, package management, unit-testing and virtualization together with Continuous Integration approach. 60-years old COBOL fits modern software engineering.

您已经通过使用Git库,程序包管理,单元测试和虚拟化以及持续集成方法实现了微服务。 已有60年历史的COBOL适合现代软件工程。

Please contact me if you have any corrections or feedback.

如果您有任何更正或反馈,请与我联系。

翻译自: https://habr.com/en/post/512676/

cobol 教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值