micronaut+consul builds microservice applications

Micronaut is a new generation of JVM-based full-stack microservice framework for building modular and easy-to-test microservice applications. This article briefly introduces the use of micronaut to build microservice applications through two simple examples.

1. Run a consul registration center

Download consul

Since the official website download is too slow, you can find other resources, such as this: https://download.csdn.net/download/m0_46455711/13184176

start up

Unzip the downloaded file, there is only one consul.exe file, just run it directly from the command line:

.\consul.exe agent -dev -ui

Open the browser and visit: http://localhost:8500/. If you find that you can visit, it means that the registration center consul is ready:
Insert picture description here

Two, install micronaut

  1. First of all, download the micronaut framework, which can be downloaded from the official website, but it is slower. You can download it here: https://download.csdn.net/download/m0_46455711/13184282
  2. Unzip the downloaded file and add its bin directory to the environment variable Path

Third, build a microservice application with consul as the registry

Project build command

Execute the following commands in the directory where the project is placed to build a service project:

mn create-app my-app1 --lang groovy --features hibernate-gorm,config-consul,discovery-consul

Here my-app1 is the project name, groovy is designated as the main development language, hibernate-gorm is enabled as the data framework, config-consul is the configuration center, and discovery-consul service registration discovery

Built project

After the command is executed, a project with the following directory structure will be generated in the current directory:
Generated project
open build.gradle and we can see that the related dependencies have been added, of course we can also add other dependencies here:
Insert picture description here
open the file bootstrap.yml, we You can see that the address of the service registry has been configured as local and 8500, which is the consul we ran earlier. Of course, we can also set the port of the current service here:
Insert picture description here
application.yml is configured with a h2 database and hibernate by
Insert picture description here
default : default In this case, here is gradle-6.7-bin.zip, but I found that the download can’t be downloaded for a long time, so you can manually change it to the locally downloaded zip. For example, here, I changed it to gradle-6.7-all.zip
Insert picture description here

Four, write code

1. Create a domain class (a simple understanding is the database operation class), named SomeTest:

package my.app1.domain

import grails.gorm.annotation.Entity

@Entity
class SomeTest {
    
    
    long id
    String name
}

It should be noted that the annotation @Entity is required, it indicates that this class is a domain class

2. Create a service

package my.app1.service

import grails.gorm.transactions.Transactional
import my.app1.domain.SomeTest
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.inject.Singleton

@Singleton
@Transactional
class HelloService {
    
    
    private static Logger log = LoggerFactory.getLogger(HelloService.class)

    void addSomeTest(){
    
    
        SomeTest someTest=new SomeTest()
        someTest.id=0
        someTest.name="hello"
        if(!someTest.save(flush:true)){
    
    
            log.error("保存数据到数据库出错:",someTest.getErrors())
        }
    }

    List<SomeTest> findAllSomeTest(){
    
    
       return SomeTest.findAll()
    }
}

The annotation @Singleton here indicates the monomer, and the annotation @Transactional indicates that the domain class can be used here

3. Create a controller

package my.app1.controller

import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import my.app1.domain.SomeTest
import my.app1.service.HelloService

import javax.inject.Inject

@Controller("/hello")
class HelloController {
    
    

    @Inject
    HelloService helloService

    @Get(uri="/add", produces="text/plain")
    String add() {
    
    
        helloService.addSomeTest()
        return "ok"
    }

    @Get(uri="/all", produces= MediaType.APPLICATION_JSON)
    List<SomeTest> all() {
    
    
        return helloService.findAllSomeTest()
    }

}

There is nothing to say about this, the only thing to say is that the annotation @Inject is used here to inject the service we created earlier

Up to now, we have created a microservice with database operation capabilities. Run the main method in the Application to start the microservice. After the startup is successful, use the browser to access the corresponding interface and find that there is no problem, and it is also registered in consul service.

5. Write another microservice and access it through the registry

A key requirement of the microservice framework is the registration and discovery of services and the invocation between services. Through the previous description, we know that micronaut has integrated the consul client, and can automatically register to the service registry after the service is started through a simple configuration. Of course, micronaut also provides good support for service discovery and service invocation.

1. Create a new microservice

mn create-app my-app2 --lang groovy --features hibernate-gorm,config-consul,discovery-consul

2. Set the service port

micronaut:
  server:
    port: 8082

3. Create a new controller

package my.app2

import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import org.slf4j.Logger
import org.slf4j.LoggerFactory

@Controller("/hello")
class HelloController {
    
    

    private static Logger log = LoggerFactory.getLogger(HelloController.class)
    
    @Get(uri="/", produces="text/plain")
    String index() {
    
    
        log.info("im hello two")
        "im hello two"
    }
}

4. Add a service to call the client in the microservice my-app1

package my.app1.client

import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
import io.micronaut.retry.annotation.Retryable

@Client("myApp2")
@Retryable
interface HelloClient {
    
    
    @Get(value = "/hello", processes = MediaType.TEXT_PLAIN)
    String hello()
}

The annotation @Client identifies this interface as a service call interface, and myApp2 is the service name (after the command is used to build my-app2, the created service name is myApp2, which can be viewed and modified in the configuration file bootstrap.yml), and it is also worth noting The service name here can also be replaced with the specific http address and port of the called service.

5. Add a fallback to the microservice my-app1 to make the called interface return a default value when the service is unavailable

package my.app1.client;

import io.micronaut.retry.annotation.Fallback;
import io.micronaut.retry.annotation.Recoverable;

@Fallback
@Recoverable
public class HelloFallback implements HelloClient {
    
    

    @Override
    public String hello() {
    
    
        return "i am hello fallback";
    }
}

What needs to be noted here is that it must be a java file instead of a groovy file. I don't know the specific reason. I am very depressed.

6. Use the service to call the client in the microservice my-app1

Insert picture description here

Use @Inject to inject the client, call the service interface like a normal method

7. Start the newly created service my-app2 and restart the service my-app1

Browser access: http://localhost:8081/hello/add, you can see the return: ok im hello two

to sum up

There is nothing to summarize, just paste the download address of the example
https://gitee.com/luoye_lj/micronaut_example

micronaut_cloud_examples.zip

Guess you like

Origin blog.csdn.net/m0_46455711/article/details/110085955