Kamoo Quarkus e kopanyang MicroProfile le Selemo

Lumelang bohle, poso ea boraro ke ena letotong la Quarkus!

Kamoo Quarkus e kopanyang MicroProfile le Selemo

Ha ho etsoa li-microservices tsa Java, hangata ho lumeloa hore Eclipse MicroProfile и Boot ea selemo ke li-API tse arohaneng le tse ikemetseng. Ka ho sa feleng, baetsi ba mananeo ba tloaetse ho sebelisa li-API tseo ba seng ba li tloaetse, kaha ho ithuta meralo e mecha le likarolo tsa nako ea ho sebetsa ho nka nako e ngata. Kajeno re tla leka ho nolofatsa ntshetsopele ea tse ling tse ratoang MicroProfile API bakeng sa baetsi ba Selemo le ho u bontša mokhoa oa ho sebelisa API ea selemo ka nako e le 'ngoe le likarolo tse ncha tsa bohlokoa quarkus.

Ka lintlha tse ling, re tla qala ka ho sheba boholo le lintlha tsa hore na Quarkus e ts'ehetsa li-API tsa selemo joang ho bonts'a baetsi ba Selemo mokhoa oa ho sebelisa MicroProfile API mosebetsing oa bona oa letsatsi le letsatsi. Ebe re tla koahela MicroProfile APIs, e leng molemo ho baetsi ba Selemo ha ba theha li-microservices.

Ke hobane'ng ha Quarkus? Taba ea pele, ena ke ho kenya likhoutu ka boits'oaro, ke hore, ho kenya bocha liphetoho tse fumanehang ho MicroProfile API, Spring API le li-API tse ling tsa Java, tse etsoang ka taelo e le 'ngoe feela: mvn quarkus:dev. Ea bobeli, ho buisanoa ka eona mohlaleng oa rona tšebeletso ea Batho (e kopanyang ho tloha Spring, MicroProfile, le JPA APIs ho ea ho binary e sebelisang setšoantšo sa GraalVM sa tlhaho) e qala ka metsotsoana e 0.055 feela 'me e nka hoo e ka bang 90 MB ea RAM (RSS) qetellong ea kopo ea RESTful. Ho feta moo, pokello ea eona ka boeona e etsoa ka taelo e le 'ngoe feela: sephutheloana sa mvn -Pnative.

Re ke ke ra bua ka botlalo ka MicroProfile, ntle le ho thusa baetsi ba Selemo ho utloisisa hore na ba ka sebelisa li-API tsa Spring joang ka MicroProfile APIs ho Quarkus.

Lijana le Kubernetes

Ho boloka sengoloa sena se le bonolo, re tla akaretsa feela likarolo tsa boemo bo holimo tsa tšehetso mona. Kubernetes, hobane ho bohlokoa ho utloisisa. Quarkus e behiloe joalo ka stack ea Java bakeng sa Kubernetes, e etselitsoe ho fokotsa tšebeliso ea memori le nako ea ho qala ea lits'ebetso le lits'ebeletso tsa Java, 'me, ka lebaka leo, ho eketsa letsoalo la bona ho moamoheli le ho fokotsa litšenyehelo ka kakaretso.

Quarks le eona e tšehetsa tlhahiso ea likoloi Lisebelisoa le litlhahiso tsa Kubernetes batataisi bakeng sa ho romelloa sethaleng sa Kubernetes le Red Hat OpenShift. Ho feta moo, Quarkus e iketsetsa lifaele tsa Dockerfile.jvm (JVM packaging) le Dockerfile.native (native binary packaging) tse hlokahalang ho theha lijana.

Qetellong, ka ho lebisa tlhokomelo ho Kubernetes e le sebaka sa ho tsamaisoa ha sepheo, Quarkus ha e sebelise mekhoa ea Java maemong ao ts'ebetso e ts'oanang e kenngoa boemong ba sethaleng sa Kubernetes ka boeona. Letlapa la 1 le fana ka 'mapa oa mangolo a sebetsang pakeng tsa Kubernetes le mekhoa e tloaelehileng ea Java e sebelisoang ke baetsi ba Spring.

Letlapa la 1. 'Mapa oa mangolo a sebetsang pakeng tsa mekhoa ea Java le Kubernetes.

Sebetsa
Traditional Spring Boot
Kubernetes

Ho sibolloa ha litšebeletso
Eureka
DNS

phetolo
Spring Cloud Config
Lokisa 'mapa/Liphiri

Meroalo e boima
Ribone (lehlakore la moreki)
Tšebeletso, Replication Controller (lehlakore la seva)

Ho bokella le ho tsamaisa khoutu ho tsoa mohlaleng

Sehloohong sena re bua ka mohlala morero, moo Spring le MicroProfile APIs esita le sehlopha se tšoanang sa Java se sebelisoang hammoho. Khoutu e mohlaleng ona e ka hlophisoa 'me ea matha ho tloha moleng oa taelo, sheba faele ea README.md bakeng sa lintlha.

Spring Framework APIs

Ente ea ho itšepa

Quarkus e tšehetsa mefuta e mengata ea Contexts and Dependency Injection (CDI) APIs le Spring Dependency Injection (Spring DI) APIs. Haeba u sebetsa le MicroProfile, Java EE le Jakarta EE, joale u se u ntse u tloaelane haholo le CDI. Ka lehlakoreng le leng, bahlahisi ba Selemo ba ka sebelisa Keketso ea Quarkus bakeng sa Spring DI API ho fihlela tšebelisano le Spring DI. Mehlala ea ho sebelisa li-API tsa Spring DI tse tšehetsoeng li fanoe ho Lethathamo la 2.

В morero ho tsoa mohlaleng oa rona E sebelisa bobeli CDI le Spring Dependency Injection. Lintlha tse ling le mehlala ka taba ena li ka fumanoa ho tataiso ea Quarkus e bitsoang Tataiso ea selemo ea DI.

Lethathamo la 2. Mehlala ea ho sebelisa li-API tsa Spring DI tse tšehetsoeng.

Likarolo tsa DI tsa selemo tse tšehelitsoeng
mehlala

Ente ea Moetsi

public PersonSpringController(
   PersonSpringRepository personRepository,  // injected      
   PersonSpringMPService personService) {    // injected
      this.personRepository = personRepository;
      this.personService = personService;
}

Ente ea Tšimo
Autowired
latela boleng ba

@Autowired
@RestClient
SalutationRestClient salutationRestClient;

@Value("${fallbackSalutation}")
String fallbackSalutation;

Bean
@Configuration

@Configuration
public class AppConfiguration {
   @Bean(name = "capitalizeFunction")
   public StringFunction capitalizer() {
      return String::toUpperCase;
   }
}

Sehlopha

@Component("noopFunction")
public class NoOpSingleStringFunction implements StringFunction {
   @Override
   public String apply(String s) {
      return s;
   }
}

Service

@Service
public class MessageProducer {
   @Value("${greeting.message}")
   String message;

   public String getPrefix() {
      return message;
   }
}

Moralo oa webo

Basebelisi ba MicroProfile ba tla rata hore Quarkus e ts'ehetsa JAX-RS, MicroProfile Rest Client, JSON-P, le JSON-B joalo ka mohlala oa mantlha oa lenaneo la webo. Bahlahisi ba selemo ba tla thabela tšehetso ea morao-rao ea Quarkus bakeng sa Spring Web API, haholo-holo li-interface tsa REST. E ts'oanang le Spring DI, sepheo se seholo sa tšehetso ea Spring Web API ke ho nolofalletsa baetsi ba Selemo ho sebelisa Spring Web APIs hammoho le MicroProfile APIs. Mehlala ea mokhoa oa ho sebelisa li-API tsa Websaete tse tšehetsoeng li fanoe ho Lethathamo la 3, 'me boitsebiso bo eketsehileng le mehlala ka taba ena e ka fumanoa thutong ea Quarkus e bitsoang. Spring Web Guide.

Lethathamo la 3. Mehlala ea ho sebelisa li-API tsa Spring Web tse tšehetsoeng.

Litšobotsi tsa Websaete tsa Selemo tse tšehelitsoeng
mehlala

@RestController
@RequestMapping

@RestController
@RequestMapping("/person")
public class PersonSpringController {
   ...
   ...
   ...
}

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@RequestParam
@RequestHeader
@MatrixVariable
@PathVariable
@CookieValue
@RequestBody
@ResponseStatus
@ExceptionHandler
@RestControllerAdvice (karolelano)

@GetMapping(path = "/greet/{id}",
   produces = "text/plain")
   public String greetPerson(
   @PathVariable(name = "id") long id) {
   ...
   ...
   ...
}

Lintlha tsa Selemo JPA

Basebelisi ba MicroProfile le bona ba tla ananela hore Quarkus e tšehetsa JPA e sebelisa Hibernate ORM. Ho boetse ho na le litaba tse monate bakeng sa bahlahisi ba Selemo: Quarkus e ts'ehetsa litlatsetso le mefuta e tloaelehileng ea Spring Data JPA. Mehlala ea ho sebelisa li-API tsa Spring Data JPA API li fanoe ho Lethathamo la 4.
В morero ho tsoa mohlaleng oa rona Spring Data JPA APIs li sebelisoa 'me boitsebiso bo eketsehileng bo fumaneha thutong ea Quarkus e bitsoang Tataiso ea JPA Data ea Selemo.

Letlapa la 4. Mehlala ea ho sebelisa li-API tsa Spring Data JPA tse tšehetsoeng.

Lintlha tse tšehetsoeng tsa Spring Data JPA Features
mehlala

CrudRepository

public interface PersonRepository
         extends JpaRepository,
                 PersonFragment {
   ...
}

Repository
JpaRepository
PagingAndSortingRepository

public class PersonRepository extends 

    Repository {

    Person save(Person entity);

    Optional findById(Person entity);
}

Likhechana tsa polokelo

public interface PersonRepository
         extends JpaRepository,
                 PersonFragment {
   ...
}

Mekhoa ea ho botsa lipotso

public interface PersonRepository extends CrudRepository {

    List findByName(String name);
    
    Person findByNameBySsn(String ssn);
    
    Optional 
       findByNameBySsnIgnoreCase(String ssn);

    Boolean existsBookByYearOfBirthBetween(
            Integer start, Integer end);
}

Lipotso tse hlalosoang ke basebelisi

public interface MovieRepository
         extends CrudRepository {

    Movie findFirstByOrderByDurationDesc();

    @Query("select m from Movie m where m.rating = ?1")
    Iterator findByRating(String rating);

    @Query("from Movie where title = ?1")
    Movie findByTitle(String title);
}

MicroProfile APIs

Ho mamella liphoso

Mehaho ea mamello ea liphoso e bohlokoa haholo bakeng sa ho thibela liphoso tse fokolang le ho theha meralo e tšepahalang ea microservice. Bahlahisi ba selemo ba 'nile ba sebelisa li-circuit-breakers bakeng sa mamello ea liphoso ka lilemo tse ngata. Hystrix. Leha ho le joalo, Hystrix ha e so ntlafatsoe nako e telele, empa MicroProfile's Fault Tolerance e se e ntse e tsoela pele ka mafolofolo mme e na le lilemo tse 'maloa tsa tšebeliso ea tlhahiso ka morao ho eona. Ka hona, ho ntlafatsa ho tšepahala ha litšebeletso ho Quarkus, ho kgothaletswa ho sebelisa MicroProfile Fault Tolerance APIs, mehlala ea eona e sebelisoang Lethathamong la 5. Bakeng sa boitsebiso bo eketsehileng mabapi le sena, bona buka ea Quarkus Tataiso ea ho mamellana ha liphoso.

Letlapa la 5. Mehlala ea ho sebelisa li-API tse tšehetsoeng ke MicroProfile Fault Tolerance.

Likarolo tsa Mamello ea Phoso ea MicroProfile
tlhaloso
mehlala

@Asynchronous

Ho etsa logic ka khoele e ka thoko

@Asynchronous
@Retry
public Future<String> getSalutation() {
   ...
   return future;
}

@Bulkhead

Fokotsa palo ea likopo tsa nako e le 'ngoe

@Bulkhead(5)
public void fiveConcurrent() {
   makeRemoteCall(); //...
}

@CircuitBreaker

Smart ho hloleha ho sebetsana le ho hlaphoheloa ho tloha ho hloleha

@CircuitBreaker(delay=500   // milliseconds
   failureRatio = .75,
   requestVolumeThreshold = 20,
   successThreshold = 5)
@Fallback(fallbackMethod = "fallback")
public String getSalutation() {
   makeRemoteCall(); //...
}

@Boela morao

Ho bitsa logic enngwe ha ho ka hloleha

@Timeout(500) // milliseconds
@Fallback(fallbackMethod = "fallback")
public String getSalutation() {
   makeRemoteCall(); //...
}

public String fallback() {
   return "hello";
}

Leka hape

Leka hape ha kopo e hlolehile

@Retry(maxRetries=3)
public String getSalutation() {
   makeRemoteCall(); //...
}

Khefutso

Ho hloleha ho laola nako

@Timeout(value = 500 )   // milliseconds
@Fallback(fallbackMethod = "fallback")
public String getSalutation() {
   makeRemoteCall(); //...
}

Litšebeletso tsa ho hlahloba (Bophelo ba Ts'ebeletso)

Li-platform tsa Kubernetes li lekola bophelo bo botle ba lijana tse sebelisang lits'ebeletso tse khethehileng. Ho lumella sethala sa motheo ho beha lits'ebeletso ho lekola lits'ebeletso, bahlahisi ba Selemo ka tloaelo ba sebelisa HealthIndicator e tloaelehileng le Spring Boot Actuator. Ho Quarkus, sena se ka etsoa ho sebelisoa MicroProfile Health, eo ka nako e sa lekanyetsoang e etsang tlhahlobo ea bophelo, empa e ka hlophisoa hore ka nako e le 'ngoe e hlahlobe bophelo le ho itokisetsa. Mehlala ea mokhoa oa ho sebelisa li-API tsa bophelo bo botle tsa MicroProfile tse tšehetsoeng li fanoe ho Lethathamo la 6, 'me boitsebiso bo eketsehileng bo fanoe bukeng ea Quarkus. Tataiso ea Bophelo bo Botle.

Letlapa la 6: Mehlala ea tšebeliso ea MicroProfile Health APIs e tšehetsoeng.

Likarolo tsa Bophelo bo Botle ba MicroProfile
tlhaloso
mehlala

@Liveness

Sethala se qalisa bocha lits'ebetso tse kentsoeng ka har'a sesebelisoa
Qetello:
moamoheli:8080/health/live

@Liveness
public class MyHC implements HealthCheck {
  public HealthCheckResponse call() {

   ...
   return HealthCheckResponse
     .named("myHCProbe")
     .status(ready ? true:false)
     .withData("mydata", data)
     .build();  
}

@Go ipaakanya

Sethala se ke ke sa romela sephethephethe ho lits'ebetso tse nang le lisebelisoa haeba se sa itokisetsa
Qetello:
moamoheli:8080/health/ready

@Readiness
public class MyHC implements HealthCheck {
  public HealthCheckResponse call() {

   ...
   return HealthCheckResponse
     .named("myHCProbe")
     .status(live ? true:false)
     .withData("mydata", data)
     .build();  
}

Melemo

Likopo li fana ka metrics molemong oa ts'ebetso (ho beha leihlo li-SLA tsa ts'ebetso) kapa merero e sa sebetseng (li-SLA tsa khoebo). Baetsi ba selemo ba fana ka metrics ba sebelisa Spring Boot Actuator le Micrometer. Ka lehlakoreng le leng, Quarkus e sebelisa MicroProfile Metrics ho fana ka metrics ea mantlha (JVM le sistimi e sebetsang), metrics ea barekisi (Quarkus), le metrics ea ts'ebeliso. MicroProfile Metrics e hloka hore ts'ebetsong e tšehetse liforomo tsa tlhahiso ea JSON le OpenMetrics (Prometheus). Mehlala ea ho sebelisa MicroProfile Metrics API e fanoe ho Lethathamo la 7.

В morero ho tsoa mohlaleng oa rona MicroProfile Metrics e sebelisoa ho fana ka metrics ea ts'ebeliso. Bakeng sa tlhaiso-leseling e batsi, bona buka ea Quarkus Tataiso ea Metrics.

Letlapa la 7. Mehlala ea ho sebelisa MicroProfile Metrics APIs.

Likarolo tsa Metrics ea MicroProfile
tlhaloso
mehlala

@Ho baloa

E supa khaontara e balang palo ea makhetlo ao ntho e tšoailoeng e bitsitsoeng ka eona

@Counted(name = "fallbackCounter", 
  displayName = "Fallback Counter", 
  description = "Fallback Counter")
public String salutationFallback() {
   return fallbackSalutation;
}

@ConcurrentGauge

E bolela sekala se balang palo ea mehala ea nako e le 'ngoe ho ea ho ntho e hlalositsoeng

@ConcurrentGuage(
  name = "fallbackConcurrentGauge", 
  displayName="Fallback Concurrent", 
  description="Fallback Concurrent")
public String salutationFallback() {
   return fallbackSalutation;
}

@Gauge

E supa sensara sa gauge se lekanyang boleng ba ntho e annoted

@Metered(name = "FallbackGauge",
   displayName="Fallback Gauge",
   description="Fallback frequency")
public String salutationFallback() {
   return fallbackSalutation;
}

@Metered

E supa sensara sa metha e lekola maqhubu a mohala oa ntho e hlahisoeng

@Metered(name = "MeteredFallback",
   displayName="Metered Fallback",
   description="Fallback frequency")
public String salutationFallback() {
   return fallbackSalutation;
}

Metric

Tlhaloso e nang le tlhahisoleseling mabapi le metadata ha kopo e amoheloa ea ho kenya kapa ho hlahisa metric

@Metric
@Metered(name = "MeteredFallback",
   displayName="Metered Fallback",
   description="Fallback frequency")
public String salutationFallback() {
   return fallbackSalutation;
}

Nako

E supa sebali sa nako se latedisang nako ya ntho e itseng

@Timed(name = "TimedFallback",
   displayName="Timed Fallback",
   description="Fallback delay")
public String salutationFallback() {
   return fallbackSalutation;
}

Metrics Endpoints

Metrics ea kopo Localhost:8080/metrics/application
Metrics ea mantlha Localhost:8080/metrics/base
Metrics ea barekisi Localhost:8080/metrics/morekisi
Metrics kaofela Localhost:8080/metrics

Moreki oa Phomolo ea MicroProfile

Hangata li-Microservices li fana ka lintlha tse RESTful tse hlokang hore li-API tsa bareki tse tsamaisanang li sebetse le tsona. Ho sebelisa li-endpoints tse RESTful, baetsi ba Spring hangata ba sebelisa RestTemplate. Quarkus e fana ka MicroProfile Rest Client APIs ho rarolla bothata bona, mehlala ea ts'ebeliso ea eona e fanoeng ho Lethathamo la 8.

В morero ho tsoa mohlaleng oa rona ts'ebeliso ea li-endpoints tsa RESTful e etsoa ho sebelisoa Client ea MicroProfile Rest. Lintlha tse ling le mehlala mabapi le sehlooho sena li ka fumanoa bukeng ea Quarkus Phomola Client Guide.

Letlapa la 8. Mehlala ea ho sebelisa MicroProfile Rest Client APIs.

Likarolo tsa Bareki ba Phomolo ea MicroProfile
tlhaloso
mehlala

@RegisterRestClient

E ngolisa Java interface e tlatsitsoeng joalo ka moreki oa REST

@RegisterRestClient
@Path("/")
public interface MyRestClient {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSalutation();
}

@RestClient

E tšoaea ts'ebetsong ea mohlala oa sebopeho sa moreki se thaepileng sa REST

@Autowired // or @Inject
@RestClient
MyRestClient restClient;

Pōpo

E letsetsa REST pheletso

System.out.println(
   restClient.getSalutation());

mp-rest/url

E totobatsa ntlha ea REST

application.properties:
org.example.MyRestClient/mp-rest/url=
   http://localhost:8081/myendpoint

Liphello

Ho blog ena, e shebaneng haholo le bahlahisi ba Selemo, re ile ra shebisisa ka potlako mokhoa oa ho sebelisa li-API tsa Selemo ka MicroProfile APIs ho Quarkus ho nts'etsapele li-microservices tsa Java ebe li li bokella ka khoutu ea tlhaho ea binary e bolokang makholo a megabyte ea RAM le ho qala ho taba ea milliseconds.

Joalo ka ha u se u ntse u utloisisa, tlhaiso-leseling e batsi mabapi le ts'ehetso ea Spring le MicroProfile APIs, hammoho le tlhaiso-leseling e ngata ea bohlokoa, e ka fumanoa ho Libuka tsa Quarkus.

Source: www.habr.com

Eketsa ka tlhaloso