Added http type service invocation

This commit is contained in:
Amulya Varote 2022-01-27 14:13:29 -08:00 committed by Artur Souza
parent 730657e0ad
commit 725aaf3255
16 changed files with 259 additions and 116 deletions

View File

@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
namespace OrderProcessingService.controller
{
[ApiController]
[Route("order")]
public class OrderProcessingServiceController : Controller
{
[HttpGet]
public void getOrder()
{
System.Threading.Thread.Sleep(5000);
Random random = new Random();
int orderId = random.Next(1,1000);
string daprPort = "3602";
string daprUrl = "http://localhost:" + daprPort + "/v1.0/invoke/checkout/method/checkout/" + orderId;
string urlParameters = "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(daprUrl);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = client.GetAsync(urlParameters).Result;
Console.WriteLine("Order requested: " + orderId);
Console.WriteLine("Result: " + result);
}
}
}

View File

@ -1,12 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapr.AspNetCore" Version="1.4.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,30 +1,26 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapr.Client; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration;
using System.Threading; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace EventService namespace OrderProcessingService
{ {
class Program class Program
{ {
static async Task Main(string[] args) public static void Main(string[] args)
{ {
while(true) { CreateHostBuilder(args).Build().Run();
System.Threading.Thread.Sleep(5000);
Random random = new Random();
int orderId = random.Next(1,1000);
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken cancellationToken = source.Token;
using var client = new DaprClientBuilder().Build();
var result = client.CreateInvokeMethodRequest(HttpMethod.Get, "checkoutservice", "checkout/" + orderId, cancellationToken);
await client.InvokeMethodAsync(result);
Console.WriteLine("Order requested: " + orderId);
Console.WriteLine("Result: " + result);
}
} }
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
} }
} }

View File

@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:20523",
"sslPort": 44376
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"CheckoutService": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:6001;http://localhost:6005",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace OrderProcessingService
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "OrderProcessingService", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OrderProcessingService v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

View File

@ -1,36 +1,41 @@
package main package main
import ( import (
"context" "fmt"
"io/ioutil"
"log" "log"
"math/rand" "math/rand"
"time" "net/http"
"os"
"strconv" "strconv"
dapr "github.com/dapr/go-sdk/client"
"github.com/gorilla/mux"
) )
type Order struct { func getOrder(w http.ResponseWriter, r *http.Request) {
orderName string w.Header().Set("Content-Type", "application/json")
orderNum string
}
func main() {
for i := 0; i < 10; i++ {
time.Sleep(5000)
orderId := rand.Intn(1000-1) + 1 orderId := rand.Intn(1000-1) + 1
client, err := dapr.NewClient() daprPort := "3602"
if err != nil { daprUrl := "http://localhost:" + daprPort + "/v1.0/invoke/checkout/method/checkout/" + strconv.Itoa(orderId)
panic(err) response, err := http.Get(daprUrl)
}
defer client.Close()
ctx := context.Background()
result, err := client.InvokeMethod(ctx, "checkoutservice", "checkout/" + strconv.Itoa(orderId), "get") if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
result, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
log.Println("Order requested: " + strconv.Itoa(orderId)) log.Println("Order requested: " + strconv.Itoa(orderId))
log.Println("Result: ") log.Println("Result: ")
log.Println(result) log.Println(result)
}
} }
func main() {
r := mux.NewRouter()
r.HandleFunc("/order", getOrder).Methods("GET")
http.ListenAndServe(":6001", r)
}

View File

@ -5,6 +5,7 @@ go 1.17
require ( require (
github.com/dapr/go-sdk v1.2.0 // indirect github.com/dapr/go-sdk v1.2.0 // indirect
github.com/golang/protobuf v1.4.3 // indirect github.com/golang/protobuf v1.4.3 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb // indirect golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb // indirect
golang.org/x/sys v0.0.0-20201202213521-69691e467435 // indirect golang.org/x/sys v0.0.0-20201202213521-69691e467435 // indirect

View File

@ -1,36 +1,11 @@
package com.service.OrderProcessingService; package com.service.OrderProcessingService;
import io.dapr.client.DaprClient; import org.springframework.boot.SpringApplication;
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.HttpExtension;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@SpringBootApplication @SpringBootApplication
public class OrderProcessingServiceApplication { public class OrderProcessingServiceApplication {
public static void main(String[] args) {
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class); SpringApplication.run(OrderProcessingServiceApplication.class, args);
public static void main(String[] args) throws InterruptedException{
while(true) {
TimeUnit.MILLISECONDS.sleep(5000);
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
DaprClient daprClient = new DaprClientBuilder().build();
var result = daprClient.invokeMethod(
"checkoutservice",
"checkout/" + orderId,
null,
HttpExtension.GET,
String.class
);
log.info("Order requested: " + orderId);
log.info("Result: " + result);
} }
}
} }

View File

@ -0,0 +1,30 @@
package com.service.OrderProcessingService.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/")
public class OrderProcessingServiceController {
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceController.class);
@GetMapping(path="/order", produces = "application/json")
public void getOrder() {
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
String daprPort = "3602";
String daprUrl = "http://localhost:" + daprPort + "/v1.0/invoke/checkout/method/checkout/" + orderId;
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(daprUrl, String.class);
log.info("Order requested: " + orderId);
log.info("Result: " + result);
}
}

View File

@ -2321,6 +2321,11 @@
"integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==",
"dev": true "dev": true
}, },
"xhr2": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/xhr2/-/xhr2-0.2.1.tgz",
"integrity": "sha512-sID0rrVCqkVNUn8t6xuv9+6FViXjUVXq8H5rWOH2rz9fDNQEd4g0EA2XlcEdJXRz5BMEn4O1pJFdT+z4YHhoWw=="
},
"y18n": { "y18n": {
"version": "5.0.8", "version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

View File

@ -10,10 +10,10 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"dapr-client": "^1.0.2", "dapr-client": "^1.0.2",
"express": "^4.17.1" "express": "^4.17.1",
"xhr2": "^0.2.1"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.14" "nodemon": "^2.0.14"
}, }
"type": "module"
} }

View File

@ -1,30 +1,24 @@
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const daprHost = "127.0.0.1"; var XMLHttpRequest = require('xhr2');
var main = function() { const port = 6001;
for(var i=0;i<10;i++) {
sleep(5000); app.get('/order', (req, res) => {
var orderId = Math.floor(Math.random() * (1000 - 1) + 1); var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
start(orderId).catch((e) => { var daprPort = '3602';
console.error(e); var daprUrl = 'http://localhost:' + daprPort + '/v1.0/invoke/checkout/method/checkout/' + orderId;
process.exit(1); var request = new XMLHttpRequest();
}); request.open('GET', daprUrl);
} request.send();
}
async function start(orderId) {
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
const result = await client.invoker.invoke('checkoutservice' , "checkout/" + orderId , HttpMethod.GET);
console.log("Order requested: " + orderId); console.log("Order requested: " + orderId);
console.log("Result: " + result); });
}
function sleep(ms) { app.listen(port, () => {
return new Promise(resolve => setTimeout(resolve, ms)); console.log("We are live on port: " + port);
} });
main();

View File

@ -1,8 +1,6 @@
import flask import flask
import logging import logging
from Order import Order
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config["DEBUG"] = True app.config["DEBUG"] = True

View File

@ -1,24 +1,23 @@
import random import random
from time import sleep from time import sleep
import requests import requests
import flask
import logging import logging
from dapr.clients import DaprClient
logging.basicConfig(level = logging.INFO) app = flask.Flask(__name__)
app.config["DEBUG"] = True
while True: @app.route('/order', methods=['GET'])
def getOrder():
logging.basicConfig(level = logging.INFO)
sleep(random.randrange(50, 5000) / 1000) sleep(random.randrange(50, 5000) / 1000)
orderId = random.randint(1, 1000) orderId = random.randint(1, 1000)
with DaprClient() as daprClient: daprPort = '3602'
result = daprClient.invoke_method( daprUrl = 'http://localhost:' + daprPort + '/v1.0/invoke/checkout/method/checkout/' + str(orderId);
"checkoutservice", result = requests.get(daprUrl, params={})
f"checkout/{orderId}",
data=b'',
http_verb="GET"
)
logging.basicConfig(level = logging.INFO)
logging.info('Order requested: ' + str(orderId)) logging.info('Order requested: ' + str(orderId))
logging.info('Result: ' + str(result)) logging.info('Result: ' + str(result))
return str(result)
app.run(host="localhost", port=6001, debug=True)