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 link the database in Tye

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

In this issue, the editor will bring you about how to link to the database in Tye. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

Let's take a look at how to link a database in Tye.

Middleware link

Most services need external middleware to support the normal operation of applications, which generally include databases, caching middleware, message queues, file systems, and so on.

Therefore, you need to manage the link strings for these middleware in the application during the development process.

Tye provides a way to manage these link strings more easily.

Start mongo using Tye

First, we use Tye to start a mongo.

Manually create a tye.yml:

Tye.yml

Name: mongo-sampleservices:-name: mongo image: mongo env:-name: ME_CONFIG_MONGODB_ADMINUSERNAME value: root-name: ME_CONFIG_MONGODB_ADMINPASSWORD value: example-name: mongo-express image: mongo-express bindings:-port: 8081 containerPort: 8081 protocol: http env:-name: ME_CONFIG_MONGODB_ADMINUSERNAME value: root-name: ME_CONFIG_MONGODB_ADMINPASSWORD value: example

Using tye run, you can launch a mongo locally and view the data in mongo through ui in http://localhost:8081:

In fact, you are using Tye to control docker desktop to start mongo. Therefore, you need to install docker desktop locally in advance in order to start.

Of course, this is actually no different from using docker-compose.

Create an application connection mongo

Next, we create an application and connect the application to mongo.

Create the test application and install the necessary packages:

Create-tye-mongo-test.sh

Dotnet new sln-n TyeTestdotnet new webapi-n TyeTestdotnet sln. / TyeTest.sln add. / TyeTest/TyeTest.csprojdotnet add. / TyeTest/TyeTest.csproj package Microsoft.Tye.Extensions.Configuration-- version 0.6.0-alpha.21070.5dotnet add. / TyeTest/TyeTest.csproj package MongoDB.Driver

Enter Startup and register MongoClient with the container:

Startup.cs

/ / 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 = "TyeTest", Version = "v1"});}); services.AddScoped (p = > {var config = p.GetRequiredService (); var connectionString = config.GetConnectionString ("mongo"); Console.WriteLine (connectionString); var client = new MongoClient (connectionString) Return client;);}

It is worth noting that an extension method is used to read the connection string of mongo from IConfiguration:

Mongo is actually the name of the service defined in tye.

GetConnectionString is an extension method from Microsoft.Tye.Extensions.Configuration

Whether MongoClient should be a global singleton or Scope, in fact, the author has not checked the data. The actual project developer should pay attention to adjust according to the demand.

Open WeatherForecastController so that each time we accept a request, we write some data to mongo to verify the effect.

WeatherForecastController.cs

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;using MongoDB.Driver Namespace TyeTest.Controllers {[ApiController] [Route ("[controller]")] public class WeatherForecastController: ControllerBase {private static readonly string [] Summaries = new [] {"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"}; private readonly ILogger _ logger; private readonly MongoClient _ mongoClient Public WeatherForecastController (ILogger logger, MongoClient mongoClient) {_ logger = logger; _ mongoClient = mongoClient;} [HttpGet] public IEnumerable Get () {var rng = new Random () Var result = Enumerable.Range (1,5) .Select (index = > new WeatherForecast {Date = DateTime.Now.AddDays (index), TemperatureC = rng.Next (- 20,55), Summary = Summaries [rng.Next (Summaries.Length)]}) .ToArray () Var mongoCollection = _ mongoClient.GetDatabase (nameof (WeatherForecast)) .GetCollection (nameof (WeatherForecast)); mongoCollection.InsertMany (result); return result;}

At this point, the test application is created. The expected effect is that when a request is received, some data is written to the WeatherForecast collection in mongo. You can view it through mongo express UI.

Modify tye.yml to configure link strings

Because of the previous, we created the tye.yml manually. Therefore, we are now making changes directly on the original basis in order to add the test application.

First, place the previously created tye.yml in the root directory of the TyeTest.sln.

Then modify it to the following form:

Tye.yml

Name: mongo-sampleservices:-name: mongo image: mongo env:-name: ME_CONFIG_MONGODB_ADMINUSERNAME value: root-name: ME_CONFIG_MONGODB_ADMINPASSWORD value: example bindings:-containerPort: 27017 connectionString: 'mongodb://$ {host}: ${port}'-name: mongo-express image: mongo-express bindings:-port: 8081 containerPort: 8081 protocol : http env:-name: ME_CONFIG_MONGODB_ADMINUSERNAME value: root-name: ME_CONFIG_MONGODB_ADMINPASSWORD value: example-name: tyetest project: TyeTest/TyeTest.csproj

Before the comparison, there are two changes:

Added nodes configured by tyetest services so that the test application can be started

Bindings has been added to mongo services. This is a way of interconnecting organizational services in tye. ConnectionString is the link string used by other services to connect to mongo.

After the modification. Use tye run to start the application.

Open the swagger page and visit API, and you can see that the data has been successfully written in mongo express:

After viewing the effect, you can use Ctrl+C to stop tye to remove the related container.

The above is the editor for you to share how to link to the database in Tye, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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

Servers

Wechat

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

12
Report