Generate Numeric Key For Microservices

Posted on by
Generate Numeric Key For Microservices Rating: 3,8/5 6430 votes

Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities. The microservice architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack. Hands-On Enterprise Java Microservices with Eclipse MicroProfile. An effective guide to designing, building, and deploying enterprise Java microservices with Eclipse MicroProfile. Key Features. Create cloud-native microservices with ease using this detailed guide; Avoid vendor lock-in when implementing microservices using Eclipse MicroProfile.

-->

This section outlines how to create a simple microservice that performs create, read, update, and delete (CRUD) operations on a data source.

We are currently using auto-generated primary keys and we would like to switch to an approach which is more suitable for microservices-based applications: either we are going to use business defined primary key (a tax code for persons) or global unique identifiers. For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt, nextDouble, nextLong etc using that instance. We can generate random numbers of types integers, float, double, long, booleans using this class. Microservices as the goal - making the adoption of microservices the goal and measuring success in terms of the number of services written Scattershot adoption - multiple application development teams attempt to adopt the microservice architecture without any coordination Trying to fly before you can walk. Hey, thanks for clarifying it over the comments. So I’ll try to give my own opinion about how would all these make sense. I must say, I don’t agree w/ everything in the article you’ve shared. Create microservices corresponding to specific functionalities. For example, an analytics application can have a chatbot functionality, a visual dashboard, a data analytics functionality and more.

Designing a simple CRUD microservice

From a design point of view, this type of containerized microservice is very simple. Perhaps the problem to solve is simple, or perhaps the implementation is only a proof of concept.

Figure 6-4. Internal design for simple CRUD microservices

An example of this kind of simple], as shown in the ConfigureServices method in an earlier code example.

However, for production environments, you might want to explore additional ways on how to store secrets like the connection strings. An excellent way to manage application secrets is using Azure Key Vault.

Azure Key Vault helps to store and safeguard cryptographic keys and secrets used by your cloud applications and services. A secret is anything you want to keep strict control of, like API keys, connection strings, passwords, etc. and strict control includes usage logging, setting expiration, managing access, among others.

Azure Key Vault allows a very detailed control level of the application secrets usage without the need to let anyone know them. The secrets can even be rotated for enhanced security without disrupting development or operations.

Applications have to be registered in the organization's Active Directory, so they can use the Key Vault.

You can check the Key Vault Concepts documentation for more details.

Implementing versioning in ASP.NET Web APIs

As business requirements change, new collections of resources may be added, the relationships between resources might change, and the structure of the data in resources might be amended. Updating a Web API to handle new requirements is a relatively straightforward process, but you must consider the effects that such changes will have on client applications consuming the Web API. Although the developer designing and implementing a Web API has full control over that API, the developer does not have the same degree of control over client applications that might be built by third party organizations operating remotely.

Versioning enables a Web API to indicate the features and resources that it exposes. A client application can then submit requests to a specific version of a feature or resource. There are several approaches to implement versioning:

Generate Numeric Key For Microservices Free

  • URI versioning

  • Query string versioning

  • Header versioning

Query string and URI versioning are the simplest to implement. Header versioning is a good approach. However, header versioning not as explicit and straightforward as URI versioning. Because URL versioning is the simplest and most explicit, the eShopOnContainers sample application uses URI versioning.

With URI versioning, as in the eShopOnContainers sample application, each time you modify the Web API or change the schema of resources, you add a version number to the URI for each resource. Existing URIs should continue to operate as before, returning resources that conform to the schema that matches the requested version.

Generate Numeric Key For Microservices In Java

As shown in the following code example, the version can be set by using the Route attribute in the Web API controller, which makes the version explicit in the URI (v1 in this case).

This versioning mechanism is simple and depends on the server routing the request to the appropriate endpoint. However, for a more sophisticated versioning and the best method when using REST, you should use hypermedia and implement HATEOAS (Hypertext as the Engine of Application State).

Additional resources

  • Scott Hanselman. ASP.NET Core RESTful Web API versioning made easy
    https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

  • Versioning a RESTful web API
    https://docs.microsoft.com/azure/architecture/best-practices/api-design#versioning-a-restful-web-api

  • Roy Fielding. Versioning, Hypermedia, and REST
    https://www.infoq.com/articles/roy-fielding-on-versioning

Generating Swagger description metadata from your ASP.NET Core Web API

Swagger is a commonly used open source framework backed by a large ecosystem of tools that helps you design, build, document, and consume your RESTful APIs. It is becoming the standard for the APIs description metadata domain. You should include Swagger description metadata with any kind of microservice, eitherll cover in some detail in this guide but there's also the option to use NSwag, which can generate Typescript and C# API clients, as well as C# controllers, from a Swagger or OpenAPI specification and even by scanning the .dll that contains the controllers, using NSwagStudio.

How to automate API Swagger metadata generation with the Swashbuckle NuGet package

Generating Swagger metadata manually (in a JSON or YAML file) can be tedious work. However, you can automate API discovery of ASP.NET Web API services by using the Swashbuckle NuGet package to dynamically generate Swagger API metadata.

Swashbuckle automatically generates Swagger metadata for your ASP.NET Web API projects. It supports ASP.NET Core Web API projects and the traditional ASP.NET Web API and any other flavor, such as Azure API App, Azure Mobile App, Azure Service Fabric microservices based on ASP.NET. It also supports plain Web API deployed on containers, as in for the reference application.

Swashbuckle combines API Explorer and Swagger or swagger-ui to provide a rich discovery and documentation experience for your API consumers. In addition to its Swagger metadata generator engine, Swashbuckle also contains an embedded version of swagger-ui, which it will automatically serve up once Swashbuckle is installed.

This means you can complement your API with a nice discovery UI to help developers to use your API. It requires a very small amount of code and maintenance because it is automatically generated, allowing you to focus on building your API. The result for the API Explorer looks like Figure 6-8.

Figure 6-8. Swashbuckle API Explorer based on Swagger metadata—eShopOnContainers catalog microservice

The Swashbuckle generated Swagger UI API documentation includes all published actions. The API explorer is not the most important thing here. Once you have a Web API that can describe itself in Swagger metadata, your API can be used seamlessly from Swagger-based tools, including client proxy-class code generators that can target many platforms. For example, as mentioned, AutoRest automatically generates .NET client classes. But additional tools like swagger-codegen are also available, which allow code generation of API client libraries, server stubs, and documentation automatically.

Currently, Swashbuckle consists of five internal NuGet packages under the high-level meta- package Swashbuckle.AspNetCore for ASP.NET Core applications.

After you have installed these NuGet packages in your Web API project, you need to configure Swagger in the Startup class, as in the following simplified code:

Once this is done, you can start your application and browse the following Swagger JSON and UI endpoints using URLs like these:

You previously saw the generated UI created by Swashbuckle for a URL like http://<your-root-url>/swagger. In Figure 6-9 you can also see how you can test any API method.

Figure 6-9. Swashbuckle UI testing the Catalog/Items API method

The Swagger UI API detail shows a sample of the response and can be used to execute the real API, which is great for developer discovery. Figure 6-10 shows the Swagger JSON metadata generated from the eShopOnContainers microservice (which is what the tools use underneath) when you request http://<your-root-url>/swagger/v1/swagger.json using Postman.

Figure 6-10. Swagger JSON metadata

It is that simple. And because it is automatically generated, the Swagger metadata will grow when you add more functionality to your API.

Additional resources

  • ASP.NET Web API Help Pages using Swagger
    https://docs.microsoft.com/aspnet/core/tutorials/web-api-help-pages-using-swagger

  • Get started with Swashbuckle and ASP.NET Core
    https://docs.microsoft.com/aspnet/core/tutorials/getting-started-with-swashbuckle

  • Get started with NSwag and ASP.NET Core
    https://docs.microsoft.com/aspnet/core/tutorials/getting-started-with-nswag

Developing a microservice for the cloud today requires modern tools. This microservices example explores using the Helidon server along with Docker to make a cloud-ready application.

Helidon Server

The Helidon server is a collection of Java libraries for writing Microservices applications in a cloud environment. Key features of Helidon include:

  • Helidon is simple to use with tooling and examples to get you going quickly. The collection of libraries are fast and lightweight running on a Netty core.

  • Helidon provides familiar APIs like JAX-RS, CDI and JSON-P/B.

  • Helidon is lightweight, flexible, and reactive and provides a modern functional programming model.

  • Helidon provides support for health checks, metrics, tracing and fault tolerance. In addition, Helidon integrates with Prometheus, Zipkin and Kubernetes.

  • Helidon supports the MicroProfile standard.

Docker

Docker is enterprise container management software. Think of a container as a very lightweight virtual machine. A container allows you to run applications in their own isolated memory space while still maintaining access to common resources like filesystems. Containers stay lightweight by not requiring processor intensive systems like GUI support, device drivers, and other more advanced operating system components. Containers are built from images which are combined with local resources from the hosting operating system.

With Docker, a Helidon application can be packaged into an image. That image can then be passed to an orchestration system like Kubernetes. From there, the orchestration system deploys, runs, manages, sizes, and monitors the application as it runs. This provides a great degree of portability as the packaged application could be deployed to any Kubernetes cluster.

Before You Begin

It is strongly recommend that you read the preceding solution before beginning this solution. See Learn about architecting microservices-based applications on Oracle Cloud

Architecture

The following architecture diagram shows the completed RESTful Java microservices application. This microservices architecture focuses on building the actual RESTful Java application code that is deployed in Docker containers.

Figure - Completed Microservices Application Architecture


Description of 'Figure - Completed Microservices Application Architecture'
  1. The RESTful web service client application, written in HTML/CSS/JavaScript, is used to access the application. The Bootstrap and jQuery frameworks are included in the client.
  2. The client connects to the application through a network. This could be a local network on a machine or the Internet.
  3. The backend application is a set of Docker containers running Helidon servers in a Kubernetes cluster. Typically, more than one copy of the application is deployed and a load balancer is used to select which instance the client communicates with. The containers are managed by the Kubernetes cluster which automatically scales the number of instances.
  4. The application uses an Oracle database for persistence. Any stored data is pushed to the database. No state is saved in the Kubernetes cluster.

About the Application

The RESTful application you create is a simple Employee Directory application.

The application has two main parts.

  • A microservice back end (written in Java)
  • A web service client (written in HTML, CSS and JavaScript)

The two parts demonstrate how a front end interacts with a microservices back end.

Bn products generator twist key lock. The BNG6500 6500W (rated) Gas Generator features: Automatic Voltage Recognition; EPA and California Air Resources Board (CARB) certified in all 50 states; Key Electric Start; GFCI. The BNG3000 Gas Genetor offers key electric start, never flat tires and a 1 year warranty. Buy now from BN Products. The Emission Control System for these generators are warranted for standards set by the Environmental Protection Agency and also the California Air Resources Board (CARB). The output receptacles include 12V, 8.3A DC, 120V 20A GFCI and, 120/240V AC 30A Twist Lock. Each unit comes complete with stand legs. The BNG5000 5000W (rated) Gas Generator features: Automatic Voltage Recognition. Auto Idle-Down Feature. EPA and California Air Resources Board. (CARB) certified in all 50 states. The BNG7500-D4 Gas Power Generator (7500W-rated) is a portable and EPA & California Air Resources Board Certified (CARB) generator.

About the Microservices-Based Back End

The back end of the application is a microservice that's coded in Java and uses libraries from the Helidon project

Figure - Employee Classes


Description of 'Figure - Employee Classes'

The core of the application is the Main class and the EmployeeService class. The Main class loads the microservice and starts a Netty web server. The EmployeeService class defines the end points for the application and handles requests and responses. The application has only one microservice. But, a typical production application is likely to contain more services.

Note that the application is designed to be stateless. All data should be pushed to the database for persistence. This approach allows you to scale the application easily.

employee-app

The application implements the data access object (DAO) pattern and can be configured for two persistence stores. By default, the application uses a mock database written with in-memory ArrayList classes so you can test the application locally or in a Kubernetes cluster without a database connection. This configuration is selected in the srcmainresourcesapplication.yaml file by setting the drivertype to Array. This guide only covers the ArrayList version of the application without a formal database.

To connect the application to an Oracle database, edit the srcmainresourcesapplication.yaml file, fill the user, password, and hosturl properties and set the drivertype property to Oracle. This application configuration allows you to use an Oracle database as a persistence store. The code for using an Oracle database for persistence is not covered in this guide.

Note:

If more than one instance of the application is present in an application cluster, then new data is not replicated across nodes. Keep this in mind when testing.

About the Client

The client you use to access the microservice is coded using HTML, CSS, and JavaScript.

The application is written using a combination of BootStrap and jQuery. The application client is included with the source of the Java back end. When the application is built, the application directory is copied to the /public directory and is available to load from your browser at http://hostname:8080/public/index.html.

Wwe

By default, the client looks for the microservice on the current host using port 8080.

About the REST Service

The REST back end is implemented in Java using the Helidon server. The server implements a few search operations along with standard create, read, update, and delete (CRUD) operations. The list of endpoints includes:

EndpointMethodDescription
/GETGet all employees
/lastname/{name}GETSearch all lastname fields for the value provided in 'name'
/department/{name}GETSearch all department fields for the value passed in 'name'.
/title/{name}GETSearch all title fields for the value provided in 'name'.
/POSTAdd a new employee.
/{id}GETGet an employee by ID.
/{id}UPDATEUpdate an employee by ID.
/{id}DELETEDelete an Employee based on ID.