Describes how to use the Jersey client to request the Spring Boot (RESTFul) service, jerseyrestful

Source: Internet
Author: User

Describes how to use the Jersey client to request the Spring Boot (RESTFul) service, jerseyrestful

This article describes how to use the Jersey client to request the Spring Boot (RESTFul) service:

The Jersey Client obtains the Client object instance encapsulation:

@ Service ("jerseyPoolingClient") public class JerseyPoolingClientFactoryBean implements FactoryBean <Client>, InitializingBean, DisposableBean {/*** Client interface is the basic interface of the REST Client for communication with the REST server. A Client is defined as a heavyweight Object, which internally manages various objects at the underlying layer of * Client communication, such as connectors and parser. Therefore, it is not recommended to generate a large number of Client instances in the application. This requires special caution during development. In addition, this interface requires that the instance be protected by closing the connection, otherwise, memory leakage may occur */private Client client;/*** the maximum number of connections to a Client. The default value is 2000 */private int maxTotal = 2000; /*** default maximum number of connections per route */private int defaultMaxPerRoute = 1000; private ClientConfig clientConfig; public JerseyPoolingClientFactoryBean () {}/*** constructor with configuration * @ param clientConfig */public JerseyPoolingClientFactoryBean (ClientConfig clientConfig) {This. clientConfig = clientConfig;} public JerseyPoolingClientFactoryBean (int maxTotal, int defamaxmaxperroute) {this. maxTotal = maxTotal; this. defaultMaxPerRoute = defamaxmaxperroute;}/*** attention: * Details: releases the Client resource when the container is destroyed * @ author chhliu */@ Override public void destroy () throws Exception {this. client. close ();}/***** attention: * Details: Initialize the Client object in the form of a connection pool * @ author chhliu */ @ Override public void afterPropertiesSet () throws Exception {// if the constructor with ClientConfig is not used, the instance of this class is null, and the default configuration is used to initialize if (this. clientConfig = null) {final ClientConfig clientConfig = new ClientConfig (); // connection pool management instance. This class is thread-safe and supports concurrent PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager (); pcm. setMaxTotal (this. maxTotal); pcm. setdefamaxmaxperroute (this. defaultMaxPerRoute); client Config. property (ApacheClientProperties. CONNECTION_MANAGER, pcm);/** when Jersey is used to request the Spring Boot service, Spring Boot uses Jackson to parse JSON by default * while Jersey uses MOXy to parse JSON by default, when the Jersey Client wants the Spring Boot service to request resources, * This difference will lead to different server-side and Client-side POJO conversions, resulting in deserialization errors, register the Jackson feature */clientConfig in the Client Config instance. register (JacksonFeature. class); // configure the Apache Connector. The default connector is HttpUrlConnector clientConfig. connectorProvider (new ApacheConnectorP Rovider (); client = ClientBuilder. newClient (clientConfig);} else {// use ClientConfig In the constructor to initialize the Client object client = ClientBuilder. newClient (this. clientConfig) ;}}/*** attention: * Details: return the Client object. If this object is null, create a default Client * @ author chhliu */@ Override public Client getObject () throws Exception {if (null = this. client) {return ClientBuilder. newClient ();} return this. client;}/*** attention :* Details: Obtain the Client object type * @ author chhliu */@ Override public Class <?> GetObjectType () {return (this. client = null? Client. class: this. client. getClass ();}/*** attention: * Details: whether the Client object is a singleton. The default value is Singleton * @ author chhliu */@ Override public boolean isSingleton () {return true ;}}

Encapsulation of the Request Spring Boot service:

@ Component ("jerseyClient") public class JerseyClient {@ Resource (name = "jerseyPoolingClient") private Client client;/*** attention: * Details: query objects by id * @ author chhliu */public ResultMsg <GitHubEntity> getResponseById (final String id) throws JsonProcessingException, IOException {WebTarget webTarget = client.tar get ("http: // localhost: 8080 "). path ("/github/get/user/" + id); Invocation. builder invocationBuilder = webTarget. request (MediaType. APPLICATION_JSON); GenericType <ResultMsg <GitHubEntity> genericType = new GenericType <ResultMsg <GitHubEntity> () {}; Response response = invocationBuilder. get (); if (response. getStatus () = 200) {/** when the readEntity method is called, the program automatically releases the connection * even if the readEntity method is not called, the program directly returns a generic object, the underlying layer will still release the connection */return response. readEntity (genericType);} else {ResultMsg <GitHubEntity> res = new ResultMsg <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}/ *** attention: * Details: paging query * @ author chhliu */public ResultMsg <Pager <GitHubEntity> trim (final Integer pageOffset, final Integer pageSize, final String orderColumn) {WebTarget webTarget = client.tar get ("http: // localhost: 8080 "). path ("/github/get/users/page "). queryParam ("pageOffset", pageOffset ). queryParam ("pageSize", pageSize ). queryParam ("orderColumn", orderColumn); // note that if the media type here is MediaType. APPLICATION_JSON, @ RequestBody Invocation must be added before the corresponding parameters in the service. builder invocationBuilder = webTarget. request (MediaType. APPLICATION_JSON); GenericType <ResultMsg <Pager <GitHubEntity> genericType = new GenericType <ResultMsg <Pager <GitHubEntity> () {}; Response response = invocationBuilder. get (); if (response. getStatus () = 200) {return response. readEntity (genericType);} else {ResultMsg <Pager <GitHubEntity> res = new ResultMsg <Pager <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}/ *** attention: * Details: query * @ author chhliu */public ResultMsg <List <GitHubEntity> getResponseByUsername (final String username) throws JsonProcessingException, IOException {WebTarget webTarget = client.tar get ("http: // localhost: 8080 "). path ("/github/get/users/" + username); Invocation. builder invocationBuilder = webTarget. request (MediaType. APPLICATION_JSON); GenericType <ResultMsg <List <GitHubEntity> genericType = new GenericType <ResultMsg <List <GitHubEntity> () {}; Response response = invocationBuilder. get (); if (response. getStatus () = 200) {return response. readEntity (genericType);} else {ResultMsg <List <GitHubEntity> res = new ResultMsg <List <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}/ *** attention: * Details: delete a record * @ author chhliu */public ResultMsg <GitHubEntity> deleteById (final String id) throws JsonProcessingException, IOException {WebTarget target = client.tar get ("http: // localhost: 8080 "). path ("/github/delete/" + id); GenericType <ResultMsg <GitHubEntity> genericType = new GenericType <ResultMsg <GitHubEntity> () {}; Response response = target. request (). delete (); if (response. getStatus () = 200) {return response. readEntity (genericType);} else {ResultMsg <GitHubEntity> res = new ResultMsg <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}/ *** attention: * Details: update a record * @ author chhliu */public ResultMsg <GitHubEntity> update (final GitHubEntity entity) throws JsonProcessingException, IOException {WebTarget target = client.tar get ("http: // localhost: 8080 "). path ("/github/put"); GenericType <ResultMsg <GitHubEntity> genericType = new GenericType <ResultMsg <GitHubEntity> () {}; Response response = target. request (). buildPut (Entity. entity (entity, MediaType. APPLICATION_JSON )). invoke (); if (response. getStatus () = 200) {return response. readEntity (genericType);} else {ResultMsg <GitHubEntity> res = new ResultMsg <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}/ *** attention: * Details: Insert a record * @ author chhliu */public ResultMsg <GitHubEntity> save (final GitHubEntity entity) throws JsonProcessingException, IOException {WebTarget target = client.tar get ("http: // localhost: 8080 "). path ("/github/post"); GenericType <ResultMsg <GitHubEntity> genericType = new GenericType <ResultMsg <GitHubEntity> () {}; Response response = target. request (). buildPost (Entity. entity (entity, MediaType. APPLICATION_JSON )). invoke (); if (response. getStatus () = 200) {return response. readEntity (genericType);} else {ResultMsg <GitHubEntity> res = new ResultMsg <GitHubEntity> (); res. setErrorCode (String. valueOf (response. getStatus (); res. setErrorMsg (response. getStatusInfo (). toString (); res. setOK (false); return res ;}}}

Jersey Client Interface Details

1 Client interface

A Client instance is created using ClientBuilder. A ClientConfig instance is usually used as a parameter. If we use Client client = ClientBuilder. when creating a Client instance in newClient () mode, a Client instance is created every time, but this instance is a heavyweight Object. Therefore, we recommend using the HTTP connection pool to manage connections, instead of creating a Client object for each request, the specific connection pool management method can be found in the above code example.

2 WebTarget Interface

The WebTarget interface is an interface for the REST client to locate resources. Through the WebTarget interface, we can define the specific address of the requested resource, query parameters and media type information. You can configure a WebTarget instance through method chain. However, you must note that although WebTarget is used in a similar way as StringBuffer, but the essence is different. The WebTarget method chain must set the return value of the method as the handle of the subsequent process. What does this mean? Let's look at the following examples:

Example 1: StringBuffer method chain example

StringBuffer sb = new StringBuffer ("lch"); sb. append ("hello"); sb. append ("world"); sb. append ("hello "). append ("world"); // This method achieves the same effect as the above two lines of code.

Example 2: WebTarget method chain example

// Use the method chain of a line of code to instantiate WebTarget webTarget = client.tar get ("http: // localhost: 8080"); webTarget. path ("/github/get/users/page "). queryParam ("pageOffset", pageOffset ). queryParam ("pageSize", pageSize ). queryParam ("orderColumn", orderColumn); // The method chain is used separately to instantiate WebTarget webTarget. path ("/github/get/users/page"); webTarget. queryParam ("pageOffset", pageOffset); webTarget. queryParam ("pageSize", pageSize); // the final results of the above two instantiation methods are very different. The above instantiation method is OK, no problem, there is a problem with the following instantiation method. In the following instantiation method, each row will generate a // new WebTarget object. The original WebTarget does not play any role, after all, the instances of each row are different. If we want to instantiate multiple rows, we must provide a handle for the return of each method. The method is as follows: WebTarget target = client.tar get ("http: // localhost: 8080 "); WebTarget pathTarget = target. path ("/github/get/users/page"); WebTarget paramTarget = pathTarget. queryParam ("pageOffset", pageOffset); // use the last WebTarget instance object.

3 Invocation interface

The Invocation interface is an interface that initiates a request to the REST server after the resource positioning configuration is completed. The request includes two methods: synchronous and asynchronous. The Invocation interface is defined by the internal Builder interface, the Builder interface inherits the synchronous interface SyncInvoker. Examples of asynchronous calling are as follows:

Future<ResultMsg<List<GitHubEntity>>> response = invocationBuilder.async().get(genericType);      if(response.isDone()){       return response.get();     } 

Invocation. the Builder interface instance executes GET and POST requests to submit queries and create them respectively. By default, the HTTP method calls return type is Response, and the return value of the generic type is also supported, in the above example, we use a large number of generic types, so we will not explain them too much here.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.