この記事では、ジャージークライアントの使用を紹介して、Spring Boot(Restful)サービスをリクエストし、次のように共有します。
ジャージークライアントは、クライアントオブジェクトインスタンスのカプセル化を取得します。
@service( "JerseypoolingClient")Public Class JerseyPoolingClientFactoryBeanは、FactoryBean <Client>、InitializingBean、DosusableBean { /***クライアントインターフェイスは残りのクライアントの基本的なインターフェイスであり、RESTサーバーとの通信に使用されます。クライアントは、コネクタ、パーサーなど、クライアント通信の下部にあるさまざまなオブジェクトを管理するヘビー級オブジェクトとして定義されているため、アプリケーションで多数のクライアントインスタンスを生成することは推奨されません。これは開発に必要です。さらに、このインターフェイスでは、インスタンスを閉じる必要があります。そうしないと、メモリリーク*/プライベートクライアントクライアントが発生します。 / ** *クライアントの接続の最大数、デフォルトは2000 */ private int maxtotal = 2000です。 / ***ルートあたりの接続のデフォルトの最大数*/ private int defaultmaxperroute = 1000; Private ClientConfig clientconfig; public JerseypoolingClientFactoryBean(){} / ***構成を備えたコンストラクター* @param ClientConfig* / public JerseyPoolingClientFactoryBean(ClientConfig ClientConfig){this.clientConfig = clientConfig; } public JerseypoolingClientFactoryBean(int maxtotal、int defaultmaxperroute){this.maxtotal = maxtotal; this.defaultmaxperroute = defaultmaxperroute; } / ** *注意: *詳細:コンテナが破壊されたときにクライアントリソースをリリース * @author chhliu * / @override public void destroy()throws exception {this.client.close(); } / ** * *注意: *詳細:接続プールの形でクライアントオブジェクトを初期化 * @author chhhliu * / @override public void abutpropertiesset()exception {//クライアントconfigを備えたコンストラクターが使用されない場合、クラスのインスタンスはnull、デフォルト構成が初期化されている場合(このclientconfig = null null null) clientConfig(); //接続プール管理インスタンス、このクラスはスレッドセーフであり、複数の並行操作をサポートしています。 pcm.setmaxtotal(this.maxtotal); pcm.setDefaultMaxperroute(this.defaultMaxperroute); clientConfig.Property(apacheclientProperties.connection_manager、pcm); / * * Jerseyを使用してSpring Boot Serviceを要求する場合、Spring BootはJacksonを使用してデフォルトでJSONを解析します *、JerseyはMoxyを使用してデフォルトでJSONを解析します。ジャージークライアントがスプリングブートサービスにリソースを要求したい場合、*この違いにより、サーバーとクライアントがPOJOを異なって変換します。その結果、敏arializationエラーが発生します*したがって、クライアントの構成インスタンスにジャクソン機能を登録する必要があります*/ clientConfig.register(jacksonfeature.class); //構成Apacheコネクタを使用して、デフォルトのコネクタはhttpurlconnector clientconfig.connectorprovider(new apacheconnectorprovider())です。 client = clientBuilder.NewClient(clientConfig); } else {//コンストラクターでclientConfigを使用してクライアントオブジェクトを初期化するclient client = clientBuilder.NewClient(this.ClientConfig); }} /** *注意: *詳細:クライアントオブジェクトを返します。オブジェクトがnullの場合、デフォルトのクライアントを作成します * @author chhliu */ @override public client getobject()throws exception {if(null == this.client){return clientbuilder.newclient(); } this.client; } / ** *注意: *詳細:クライアントオブジェクトのタイプを取得 * @author chhliu * / @override public class <? } / ** *注意: *詳細:クライアントオブジェクトがシングルトンであるかどうか、デフォルトでシングルトンに * @author chhliu * / @override public boolean issingleton(){return true; }}スプリングブートサービスのカプセル化のリクエスト:
@component( "Jerseyclient")Public Class Jerseyclient {@Resource(name = "JerseypoolingClient")プライベートクライアント。 /**注意: *詳細:id * @author chhliu */public resultmsg <githubentity> getResponseByid(final String ID)を介してオブジェクトをクエリします。 Invocation.Builder InvocationBuilder = webtarget.Request(mediatype.application_json); generictype <resultmsg <githubentity >> generictype = new generictype <resultmsg <githubentity >>(){}; Response Response = InvocationBuilder.get(); if(respons.getStatus()== 200){ /**準備方法が呼び出された場合、プログラムは接続*を自動的にリリースします。 } else {resultmsg <githubentity> res = new resultmsg <githubentity>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }} / ** *注意: *詳細:ページネーションクエリ * @author chhliu * / public restresmsg <pager <githubentity >> getgithubwithpager(final integer pageoffset、final integer pageize、final string webtarumn = client.target( "http:// localhost:8080").path( "/github/get/users/page").queryparam( "pageoffset"、pageoffset).queryparam( "pagesize"、pagesize).queryparam( "ordercolumn"、ordercolumn); //ここのメディアタイプがmediatype.application_jsonである場合、サービスの対応するパラメーターの前に@requestbody invocation.builder invocationbuilder = webtarget.request(mediatype.application_json)が必要であることに注意してください。 generictype <resultmsg <pager <githubentity >>>> generictype = new generictype <resultmsg <pager <githubentity >>>(){}; Response Response = InvocationBuilder.get(); if(respons.getStatus()== 200){return respons.readentity(generictype); } else {resultmsg <pager <githubentity >> res = new resultmsg <pager <githubentity >>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }} / ** *注意: *詳細:username * @author chhliu *に基づくクエリ * / public resultmsg <list <githubentity >> getResponseByUsername(final String username)throws jsonProcessingException、ioexception {webtartget webtargetget = client.target( "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(respons.getStatus()== 200){return respons.readentity(generictype); } else {resultmsg <list <githubentity >>> res = new resultmsg <list <githubentity >>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }}/** *注意: *詳細:id * @author chhliu */public resultsg <githubentity> deletebyid(final string id)throws jsonprocessingingexception、ioexception {webtarget target = client.target( "http:// localhost:8080/github")。 generictype <resultmsg <githubentity >> generictype = new generictype <resultmsg <githubentity >>(){};応答応答=ターゲット.request()。delete(); if(respons.getStatus()== 200){return respons.readentity(generictype); } else {resultmsg <githubentity> res = new resultmsg <githubentity>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }}/** *注意: *詳細:レコードを更新 * @author chhliu */public resultmsg <githubentity> update(final githubentity Entity)jsonprocessingingexception、ioexception {webtarget target = client.target( "http:// localhost:8080")。 generictype <resultmsg <githubentity >> generictype = new generictype <resultmsg <githubentity >>(){};応答応答=ターゲット.Request()。buildput(entity.entity(entity、mediatype.application_json))。invoke(); if(respons.getStatus()== 200){return respons.readentity(generictype); } else {resultmsg <githubentity> res = new resultmsg <githubentity>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }}/** *注意: *詳細:レコードを挿入 * @author chhliu */public resultmsg <githubentity> save(final githubentityエンティティ)jsonprocessingingexception、ioexception {webtarget target = client.target( "http:// localhost:8080")。 generictype <resultmsg <githubentity >> generictype = new generictype <resultmsg <githubentity >>(){};応答応答=ターゲット.request()。buildpost(entity.entity(entity、mediatype.application_json))。invoke(); if(respons.getStatus()== 200){return respons.readentity(generictype); } else {resultmsg <githubentity> res = new resultmsg <githubentity>(); Res.SetERRORCODE(String.ValueOf(respons.getStatus())); res.seterrormsg(Response.getStatusInfo()。toString()); res.setok(false); RESを返します。 }}}ジャージークライアントインターフェイスの詳細な説明
1クライアントインターフェイス
クライアントインスタンスの作成は、クライアントビルダーを介して構築されます。通常、ClientConfigインスタンスはパラメーターとして使用されます。クライアントclient = clientbuilder.newclient()を使用してクライアントインスタンスを作成する場合、毎回クライアントインスタンスを作成しますが、インスタンスはヘビー級オブジェクトです。したがって、要求するたびにクライアントオブジェクトを作成するのではなく、HTTP接続プーリングを使用して接続を管理することをお勧めします。特定の接続プール管理方法については、上記のコード例を参照してください。
2 Webtargetインターフェイス
WeBtargetインターフェイスは、RESTクライアント向けのリソースポジショニングを実装するインターフェイスです。 WeBtargetインターフェイスを介して、要求されたリソース、クエリパラメーター、メディアタイプ情報などの特定のアドレスを定義できます。メソッドチェーンを介してWebtargetインスタンスの構成を完了することができますが、WeBtargetの使用方法はStringBufferのメソッドチェーンに非常に似ていますが、本質的に異なることに注意してください。 Webtargetのメソッドチェーンは、メソッドの返品値を後続のプロセスのハンドルとして設定する必要があります。これはどういう意味ですか?次の例を参照してください。
例1:StringBufferメソッドチェーンの例
stringbuffer sb = new stringbuffer( "lch"); sb.append( "hello"); sb.append( "world"); sb.append( "hello")。append( "world"); //この方法は、上記の2行のコードと同じです。
例2:WeBtargetメソッドチェーンの例
//ワンラインコードメソッドチェーンを使用して、webtarget webtarget webtarget = client.target( "http:// localhost:8080"); webtarget.path( "/github/get/users/page").queryparam( "pageoffset"、pageoffset).queryparam( "pagesize"、pagesize).queryparam( "ordercolumn"、ordercolumn); //ここにメソッドチェーンが使用され、webtarget webtarget.path( "/github/get/users/page"); webtarget.queryparam( "pageoffset"、pageoffset); webtarget.queryparam( "pagesize"、pagesize); //上記の2つのインスタンス化方法の結果は非常に異なります。上記のインスタンス化方法は問題ありませんが、問題はありませんが、次のインスタンス化方法には問題があります。次のインスタンス化方法では、各行はA //新しいWeBtargetオブジェクトを生成します。元のWebtargetは役割を果たしませんでした。結局のところ、各行のインスタンスは異なります。複数の行でインスタンス化する場合は、各メソッドの返品のためのハンドルを提供する必要があります。メソッドは次のとおりです。WeBtargetTARGET= CLIERN.TARGET( "http:// localhost:8080"); webtarget pathtarget = target.path( "/github/get/users/page"); webtarget paramtarget = pathtarget.queryparam( "pageoffset"、pageoffset); //最後に使用するときは、最後のwebtargetインスタンスオブジェクトを使用します
3 Invocation Interface
Invocation Interfaceは、リソースの位置付け構成を完了した後、RESTサーバーへのリクエストを開始するインターフェイスです。リクエストには、同期と非同期の2つの方法が含まれています。 Invocation Interface内のビルダーインターフェイスによって定義されます。ビルダーインターフェイスは、同期インターフェイスSyncinvokerを継承します。非同期呼び出しの例は次のとおりです。
future <resultmsg <list <githubentity >>> response = vocationbuilder.async()。get(generictype); if(respons.isdone()){return respons.get(); } Invocation.Builder Interfaceインスタンスは、それぞれクエリと作成を送信するためにGETリクエストと投稿を実行します。デフォルトでは、HTTPメソッド呼び出しの返品タイプは応答タイプであり、ジェネリックタイプの戻り値もサポートします。上記の例では、多数のジェネリックを使用したため、ここではあまり説明しません。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。