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

What is the Micronaut framework and how to use it

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the relevant knowledge of "what is the Micronaut framework and how to use it". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "what is the Micronaut framework and how to use it" can help you solve the problem.

What is Micronaut?

Micronaut is a JVM-based framework for building lightweight, modular applications. Micronaut is the latest framework developed by OCI, the same company that created Grails, to make it fast and easy to create microservices.

Although Micronaut contains some features similar to existing frameworks such as Spring, it also has some new features that make it different. It provides a variety of ways to create applications through support for Java, Groovy, and Kotlin.

Main features

One of the most exciting features of Micronaut is its compile-time dependency injection mechanism. Most frameworks use reflection and proxies to perform dependency injection at run time. However, Micronaut builds its dependency injection data at compile time. The result is faster application startup and less memory footprint.

Another feature is its best-in-class support for client and server reactive programming. Because both RxJava and projectreactor are supported, the choice of a specific reactive implementation is left to the developer.

Micronaut also has some features that make it an excellent framework for developing cloud-based applications. It supports a variety of service discovery tools, such as Eureka and consur, and can be used with different distributed tracking systems such as Zipkin and Jaeger.

It also provides support for creating AWS lambda functions, making it easy to create Serverless serverless applications.

Introduction

The easiest way to get started is to use SDKMAN:

> sdk install micronaut 1.0.0.RC2

This will install all the binaries we need to build, test, and deploy the Micronaut application. It also provides Micronaut CLI tools that make it easy for us to start new projects.

In the following sections, we will introduce some of the features of the framework.

Dependency injection

As mentioned earlier, Micronaut handles dependency injection at compile time, unlike most IoC containers.

However, it still fully supports JSR-330 annotations, so using bean is similar to other IoC frameworks.

To automatically connect bean to our code, we use @ Inject:

@ Injectprivate EmployeeService service

The @ Inject annotation works like @ Autowired and can be used for fields, methods, constructors, and parameters.

By default, the scope of all bean is a prototype. We can use @ singleton to quickly create a singleton bean. If multiple classes implement the same bean interface, @ Primary can be used to resolve conflicts between them:

@ Primary@Singletonpublic class BlueCar implements Car {}

When bean is optional, you can use the @ Requires annotation, or perform an automatic join only if certain conditions are met.

In this respect, it behaves very similar to Spring Boot@Conditional annotations:

@ Singleton@Requires (beans = DataSource.class) @ Requires (property = "enabled") @ Requires (missingBeans = EmployeeService) @ Requires (sdk = Sdk.JAVA, value = "1.8") public class JdbcEmployeeService implements EmployeeService {} build HTTP server

Now let's see how to create a simple HTTP server application. First, we will create a project using SDKMAN:

> mn create-app hello-world-server-build maven

This will create a new Java project using Maven in a directory called helloworld server. In this directory, we will find the main application source code, Maven POM files, and other support files for the project.

The default application is very simple:

Public class ServerApplication {public static void main (String [] args) {Micronaut.run (ServerApplication.class);}} blocking HTTP

As far as it is concerned, this application will not have much effect. Let's add a controller with two endpoints. Both will return a greeting, but one will use the GET HTTP verb and the other will use POST:

@ Controller ("/ greet") public class GreetController {@ Inject private GreetingService greetingService; @ Get ("/ {name}") public String greet (String name) {return greetingService.getGreeting () + name;} @ Post (value = "/ {name}", consumes = MediaType.TEXT_PLAIN) public String setGreeting (@ Body String name) {return greetingService.getGreeting () + name;}} reactive IO

By default, Micronaut will implement these endpoints using the traditional blocking Imax O. However, we can quickly achieve non-blocking endpoints by changing the return type to any reactive non-blocking type.

For example, for RxJava, we can use Observable. Similarly, when using Reactor, we can return the Mono or Flux data type:

@ Get ("/ {name}") public Mono greet (String name) {return Mono.just (greetingService.getGreeting () + name);}

For both blocking and non-blocking endpoints, Netty is the underlying server used to process HTTP requests.

Typically, requests are processed in the main Icano thread pool created at startup, causing them to block.

However, when a non-blocking data type is returned from the controller endpoint, Micronaut uses the Netty event to loop the thread, making the entire request non-blocking.

Build HTTP client

Now let's build a client to use the endpoint we just created. Micronaut provides two ways to create HTTP clients:

Declarative HTTP client

Programmable HTTP client

Declarative HTTP client

The first and fastest way to create is to use a declarative approach:

@ Client ("/ greet") public interface GreetingClient {@ Get ("/ {name}") String greet (String name);}

Note that we do not implement any code to invoke our service. Instead, Micronaut understands how to invoke the service from the method signatures and annotations we provide.

To test this client, we can create a JUnit test that uses the embedded server API to run an embedded instance of our server:

Public class GreetingClientTest {private EmbeddedServer server; private GreetingClient client; @ Before public void setup () {server = ApplicationContext.run (EmbeddedServer.class); client = server.getApplicationContext () .getBean (GreetingClient.class);} @ After public void cleanup () {server.stop ();} @ Test public void testGreeting () {assertEquals ("Mike"), "Hello Mike") }} programming HTTP client

If we need more control over its behavior and implementation, we can also choose to write more traditional clients:

@ Singletonpublic class ConcreteGreetingClient {private RxHttpClient httpClient; public ConcreteGreetingClient (@ Client ("/") RxHttpClient httpClient) {this.httpClient = httpClient;} public String greet (String name) {HttpRequest req = HttpRequest.GET ("/ greet/" + name); return httpClient.retrieve (req). BlockingFirst ();} public Single greetAsync (String name) {HttpRequest req = HttpRequest.GET ("/ async/greet/" + name) Return httpClient.retrieve (req). First ("An error as occurred");}

The default HTTP client uses RxJava, so you can easily handle blocking or non-blocking calls.

Micronaut client

When we used the Micronaut CLI tool to create the sample project, we had already seen its practical application.

In our example, we created a stand-alone application, but it also has some other features.

Joint project

In Micronaut, federation is just a set of stand-alone applications located in the same directory. By using federation, we can easily manage them together and make sure they get the same default values and settings.

When we use the CLI tool to generate the union, it takes the same parameters as the create app command. It will create a top-level project structure, and each separate application will be created in its subdirectory.

Features

When creating a stand-alone application or federation, we can decide what features the application needs. This helps ensure that the project contains the smallest set of dependencies.

We use the-features parameter to specify the property and provide a comma-separated list of property names.

We can find a list of available features by running the following command:

> mn profile-info serviceProvided Features:-* annotation-api-Adds Java annotation API* config-consul-Adds support for Distributed Configuration with Consul* discovery-consul-Adds support for Service Discovery with Consul* discovery-eureka-Adds support for Service Discovery with Eureka* groovy-Creates a Groovy application [...] More features available existing projects

We can also use the CLI tool to modify an existing project. Enables us to create bean, clients, controllers, and so on. When we run the mn command in an existing project, a new set of commands will be available:

> mn help | Command Name Command Description---create-bean Creates a singleton beancreate-client Creates a client interfacecreate-controller Creates a controller and associated testcreate-job Creates a job with scheduled method's content on "what the Micronaut framework is and how to use it" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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