Dapr Java HTTP call

Zhang_Xiang 2020-11-08 16:37:45
dapr java http


Version introduction

  • Java edition :8
  • Dapr Java SKD edition :0.9.2

Dapr Java-SDK HTTP Call document There is a prerequisite , The contents are as follows :

  • Dapr and Dapr CLI.
  • Java JDK 11 (or greater): Oracle JDK or OpenJDK.
  • Apache Maven version 3.x.

We see Java JDK The minimum requirement for version is 11, But this article shows what you use JDK 8, What is the reason for that , Sure Reference resources Java-SDK Issues,Issues The answer is as follows :

We want to validate that the SDK is built with Java 8 and apps can use it with Java 11.

It means they want to pass Java 11 Write application validation Java 8 Written SDK Whether it can be used normally . This article does not need to verify Java 11 Can you use Java-SDK , So this article will use Java 8 Building the application .

Engineering structure

3 Sub project , One client, Two service. Two new service The point is to show http Link call uses dapr How to achieve .3 All the projects are integrated Spring Boot.Spring Boot Automatically register after startup Controller、Config And so on. bean.

graph LR; java-client-a--1-->java-service-b; java-service-b--2-->java-service-c; java-service-c--3-->java-service-b; java-service-b--4-->java-client-a;
  1. java-client-a Call as client java-service-b;
  2. java-service-b Receiving request , And call java-service-c;
  3. java-service-c Receiving request , And respond to ;
  4. java-service-b received java-service-c The reply , And respond to java-client-a request .

java-service-c

java-service-c As http Call the end of the link , Just listen http The request can be .

package com.dapr.service;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
/**
* @author Zhang_Xiang
* @since 2020/11/7 10:51:22
*/
public class ServiceC {
/**
* Starts the service.
*
* @param args Expects the port: -p PORT
* @throws Exception If cannot start service.
*/
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
DaprApplication.start(port);
}
}

DaprApplication.start(port); Integrate SpringBoot start-up .

package com.dapr.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Dapr's HTTP callback implementation via SpringBoot.
* Scanning package io.dapr.springboot is required.
*
* @author zhangxiang
*/
@SpringBootApplication(scanBasePackages = {"com.dapr.service"})
public class DaprApplication {
/**
* Starts Dapr's callback in a given port.
*
* @param port Port to listen to.
*/
public static void start(int port) {
SpringApplication app = new SpringApplication(DaprApplication.class);
app.run(String.format("--server.port=%d", port));
}
}

Start command :

dapr run --app-id java-service-c --app-port 9100 --dapr-http-port 3510 -- java -jar target/dapr-java-service-exec.jar com.dapr.service.ServiceC -p 9100

java-service-b

java-service-b You need to configure a DaprClient Bean, To use... When needed Http Injection of client places .

package com.dapr.service.config;
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Zhang_Xiang
* @since 2020/11/8 08:46:49
*/
@Configuration
public class Client {
@Bean
public DaprClient getClient(){
return (new DaprClientBuilder()).build();
}
}

Next, what you need to call Controller Add constructor injection to .


/**
* SpringBoot Controller to handle input binding.
*
* @author zhangxiang
*/
@RestController
public class HelloController {
private final DaprClient client;
...
public HelloController(DaprClient client) {
this.client = client;
}
...
}

launch http request .

...
byte[] response = client.invokeService(SERVICE_APP_ID, "say", message, HttpExtension.POST, null,
byte[].class).block();
if (response != null) {
...
}
...

Start command :

dapr run --app-id java-service-b --app-port 9101 --dapr-http-port 3511 -- java -jar target/dapr-java-service-exec.jar com.dapr.service.ServiceB -p 9101

java-client-a

about java-client-a Come on , Integrate Springboot Optional. , Here, construct a every 5 Second, the client that initiated a request .

package com.dapr.client;
import com.alibaba.fastjson.JSON;
import com.common.ResponseResult;
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.HttpExtension;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
/**
* @author Zhang_Xiang
* @since 2020/11/7 17:30:26
*/
public class ClientA {
/**
* Identifier in Dapr for the service this client will invoke.
*/
private static final String SERVICE_APP_ID = "java-service-b";
/**
* Format to output date and time.
*/
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* Starts the invoke client.
*
* @param args Messages to be sent as request for the invoke API.
*/
public static void main(String[] args) throws IOException {
try (DaprClient client = (new DaprClientBuilder()).build()) {
while (true) {
Calendar utcNow = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
String msg = String.format("%s:this this java client A", utcNowAsString);
byte[] response = client.invokeService(SERVICE_APP_ID, "say", msg.getBytes(), HttpExtension.POST, null,
byte[].class).block();
if (response != null) {
String responseResultStr = new String(response);
ResponseResult responseResult = JSON.parseObject(responseResultStr, ResponseResult.class);
System.out.println(responseResult.getMessage());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

Start command :

dapr run --app-id java-client-a --dapr-http-port 3006 -- java -jar target/dapr-java-client-exec.jar com.dapr.client.ClientA

summary

The starting sequence of each module shall be :

graph LR; java-service-c-->java-service-b; java-service-b-->java-client-a;

The reason why the order is limited here is , If you start first java-client-a ,java-client-a It will pass immediately dapr Start to initiate a request to java-service-b , And then java-service-b Didn't start . This will trigger dapr The retry mechanism of .

retry

Service calls when event call fails and transient errors , The interval between the execution and the backoff time is (backoff time periods) Automatic retry of .
Error causing retry :

  • Network error , Including terminal unavailable and denial of connection .
  • Authentication error , Because on caller / Of the callee dapr The side car certificate update results in .

Every time you try again, you will 1 The time of seconds is interval , The maximum number of retries is 3 Time . And the destination side car passes through gRPC Establishing a connection 5 Second timeout .

java-client-a Print :

== APP == This is java-service-b,receive the message:2020-11-08 14:21:14.336:this this java client A,and request java-service-c get the response:{"message":"This is java-service-c,receive the message:\"2020-11-08 14:21:14.336:this this java client A\""}

java-service-b Print :

== APP == This is java-service-b,receive the message:2020-11-08 14:21:44.454:this this java client A

java-service-c Print :

== APP == This is java-service-c,receive the message:"2020-11-08 14:22:19.571:this this java client A"

Open a new command line window , Input dapr list

Start example

Source code address :https://github.com/ZhangX-Byte/dapr-java

Cloning of warehouse

git clone https://github.com/ZhangX-Byte/dapr-java.git
cd dapr-java

structure dapr-java project

mvn install

Then each project is install It will start up normally .

版权声明
本文为[Zhang_Xiang]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云