Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Dapr to simplify microservices from scratch

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Dapr to simplify microservices from scratch". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Dapr to simplify microservices from scratch.

Preface

The existing micro-service model needs to integrate a large number of infrastructure modules into the business code, such as registry, service discovery, service invocation link tracking, request circuit breaker, retry current limit and so on, making the system too bloated and heavyweight.

As a new generation of micro-service mode, Dapr uses sidecar mode, simplifies the existing micro-service system code, separates the infrastructure layer in sidecar mode, and makes developers focus more on business logic writing.

This article builds a simple example of using dapr based on net6 and dapr1.5.

1. Install Docker

The operation of Dapr depends on the Docker environment.

As a learning environment, use the Centos 7 system to install Docker.

To install Docker, it is recommended to use the daocloud one-click installation command:

Curl-sSL https://get.daocloud.io/docker | sh

Run the command after the installation is complete:

[root@localhost ~] # docker-vDocker version 20.10.11, build dea9396

Shows that the corresponding Docker version is installed successfully.

2. Install Dapr CLI

Official explanation: Dapr CLI is your primary tool for various Dapr-related tasks. You can use it to run an application with Dapr sidecar, and to view sidecar logs, list running services, and run Dapr dashboards.

Download Dapr CLI

Wget-Q https://raw.githubusercontent.com/dapr/cli/master/install/install.sh-O-| / bin/bash

Verify the installation

Dapr-v

The installation is successful by outputting the following.

CLI version: 1.5.0Runtime version: 1.5.0

Due to domestic network problems, using the official Dapr installation method will generally encounter a variety of problems, so download dapr and install it through script.

Modify the hosts file

Vi / etc/hosts140.82.114.4 github.com 199.232.69.194 github.global.ssl.fastly.net140.82.114.9 codeload.github.com

Refresh the cache

Yum install-y nscdservice nscd restart

First you need to install Git, and then execute the following command:

Git clone-v https://gitee.com/Two-Twoone/dapr-installer.gitcd dapr-installer/./install.sh

It's still slow, but it's better than never.

The above command starts several containers and runs the following operations to verify:

[root@localhost dapr-installer] # docker ps-- format "table {{.ID}}\ t {{.Names}}\ t {{.Ports}}" CONTAINER ID NAMES PORTSa0565f609846 dapr_placement 0.0.0.015 50005-> 50005/tcp,:: 50005-> 50005/tcpc392f5cf7a18 dapr_redis 0.0.0.015 6379-> 6379/tcp,: 6379-> 6379/tcp2ee68c450b29 dapr_zipkin 9410/tcp, 0.0.0.009411-> 9411/tcp : 9411-> 9411/tcp3, install Net6 SDKrpm-Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm yum update yum install dotnet-sdk-6.04, create applications

Create 2 projects to reference Dapr for product,cart

Dotnet add package Dapr.AspNetCore

The AddDapr call to the Program.cs registers the DaprClient class with the ASP.NET Core injection system. After registering the client, you can now inject an instance of DaprClient into the service code to communicate with the Dapr sidecar, building blocks, and components.

Builder.Services.AddControllers (). AddDapr (); 4.1.Service invocation

In the micro-service system, the invocation between services is essential, and the difficulties mainly focus on the location of the service, how to retry when an error occurs, load balancing and so on.

Sidecar is used as the reverse proxy module of the service in Dapr to solve these problems.

The following code was added to the prodcut project

[Route ("api/ [controller]")] [ApiController] public class ProductController: ControllerBase {private ILogger _ logger; public ProductController (ILogger logger) {_ logger = logger } private static readonly List products = new List {"aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm", "nn"} [HttpGet] public ActionResult Get () {_ logger.LogInformation ($"method to get goods called"); string [] temps = new string [5]; for (int I = 0; I

< 5; i++) { Random random = new Random(Guid.NewGuid().GetHashCode()); temps[i] = products[random.Next(0, products.Count - 1)]; } return Ok( temps); } }# 启动Product 项目dapr run --app-id ProductDemo --app-port 5010 --dapr-http-port 7015 -- dotnet /root/www/product/Dapr.Product.Sample.dll --urls http://*:5010 cart项目增加下列代码,dapr支持http,grpc调用方式,这里以常用的webapi为例,使用http方式调用。 InvokeMethodAsync方法中appid对应的就是dapr run 中的appid,无需关系调用地址。 [Route("api/[controller]")] [ApiController] public class CartController : ControllerBase { private readonly DaprClient _daprClient; private readonly ILogger _logger; public CartController(DaprClient daprClient, ILogger logger) { _daprClient = daprClient; _logger = logger; } [HttpGet] [Route("GetProducts")] public async Task GetProducts() { _logger.LogInformation($" Cart 获取商品"); var products = await _daprClient.InvokeMethodAsync(HttpMethod.Get, "ProductDemo", "/api/Product/GetAll"); return Ok(products); } } 将程序上传到linux服务器,运行程序 # 启动 Cart 项目dapr run --app-id CartDemo --app-port 5020 --dapr-http-port 7025 -- dotnet /root/www/cart/Dapr.Cart.Sample.dll --urls http://*:5020 调用接口,可以看到Cart项目几乎没有代码入侵就实现了接口调用。 [root@localhost ~]# curl -X 'GET' 'http://192.168.2.110:5020/api/Cart/GetProducts'["aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn"] Dapr内部使用了mDns进行了服务注册发现和负载均衡,部署多个product后调用,可以看到轮询调用效果。 在自承载模式下,Dapr 使用 mDNS 查找它。在 Kubernetes 模式下运行时,Kubernetes DNS 服务确定地址。 在调用失败和瞬态错误的情况下,服务调用会执行自动重试,Dapr 默认是开启了重试,所以接口不支持幂等是十分危险的行为。 4.2、发布订阅 发布订阅模式,主要是用于微服务间基于消息进行相互通信。你可能也会说,这也要拿出来说,我搞个RabbitMQ/Kafka就是了, 原来我们都会根据使用的组件引入不同的sdk,不同的消息队列监听、消费模式还不一样。 Dapr 提供了一个构建基块,可显著简化实现发布/订阅功能,从而和底层基础设施解耦,编写业务逻辑时不需要关心是什么消息队列。 再Program中添加发布订阅支持 app.UseCloudEvents(); app.UseEndpoints(endpoints =>

{endpoints.MapSubscribeHandler ();})

Subscribe to messages, using the Topic feature, passing pubsub and topic names

[Topic ("pubsub", "newUser")] public ActionResult subUserInfo (UserInfo us) {_ logger.LogInformation ($"received subscription message id: {us.id} name: {us.name}, age: {us.age}, sex: {us.sex}"); return Ok ("processed");}

Publish the message, expose the method PublishEventAsync using dapr, pass the pubsub and topic name, and the message body

Public async Task PubUserInfo (UserInfo us) {await _ daprClient.PublishEventAsync ("pubsub", "newUser", us); return Ok ();}

The message publish and subscribe component supports RabbitMQ,Redis,Kafka and so on.

4.3, status management

Dapr defaults to using Redis as the state store. It also supports MongoDB,PostgreSQL,SQL Server and so on.

It does not expose the underlying middleware to the upper layer, that is, the same set of code can be used in different environments to use different middleware.

[HttpPost] [Route ("SaveUserList")] public async Task SaveUserList () {var temps = new List {new UserInfo ("Xiao Hong", 1 Regent true Guid.NewGuid (). ToString ()), new UserInfo ("Xiaohuang", 1 Regent Guid.NewGuid (). ToString ()), new UserInfo ("Little Blue", 1 true Guid.NewGuid () .ToString ()} Await _ daprClient.SaveStateAsync ("statestore", "UserList", temps); return Ok (1);} [HttpGet] [Route ("GetUserList")] public async Task GetUserList () {var list = await _ daprClient.GetStateAsync ("statestore", "UserList"); return Ok (list) } [HttpGet] [Route ("DeleteUserList")] public async Task DeleteUserList () {await _ daprClient.DeleteStateAsync ("statestore", "UserList"); return Ok (1);} public record UserInfo (string name, int age, bool sex, string id); 4.4.Link tracing

In the traditional micro-service, the code intrusion is strong in order to achieve link tracking.

Dapr adds a http/grpc middleware to Sidecar. Block all application traffic and automatically inject the associated ID to track distributed transactions.

Zipkin protocol is used for distributed tracking, no code detection is required, and all traffic is automatically tracked using a configurable trace level.

At this point, I believe you have a deeper understanding of "how to use Dapr to simplify micro-services from scratch". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report