RestTemplateアクセスProtobuf
6646 ワード
RestTemplateを使用してgoogleのprotobufにアクセスする例.実は簡単です.Client側のコードは以下の通りです.
RestTemplateのもう一つの声明では、springのxmlを使用して、HttpClientの高度な機能を利用しています.
ProtobufResult.PBResultは私がpbresult.protoに基づいて ファイル生成されたクラスファイル.
と書く
#protoc.exe ./proto/pbresult.proto --java_out=./src
サーバ側のコードで、クライアントProtobufへのメッセージを返します.
pbresult.proto
と書く
package tutorial;
option java_package = "org.kanpiaoxue.test.protobuf";
option java_outer_classname = "ProtobufResult";
message PBResult {
required int32 status = 1;
optional string statusInfo = 2;
optional string data = 3;
}
私たちはHTTPの相手にPOSTリクエストを開始する必要があります.また、postのパラメータはProtobufでカプセル化されます.もし操作したら?
送信元のspringmvcのControllerのコードを次に示します.
受信者Controlのコードは次のとおりです.
RestTemplate restTemplate = new RestTemplate();
byte[] rs = restTemplate.getForObject(url, byte[].class, args);
ProtobufResult.PBResult obj = ProtobufResult.PBResult.parseFrom(rs);
RestTemplateのもう一つの声明では、springのxmlを使用して、HttpClientの高度な機能を利用しています.
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory" />
</constructor-arg>
</bean>
ProtobufResult.PBResultは私がpbresult.protoに基づいて ファイル生成されたクラスファイル.
と書く
#protoc.exe ./proto/pbresult.proto --java_out=./src
サーバ側のコードで、クライアントProtobufへのメッセージを返します.
/**
* <pre>
* @param response
* @param status 0 , :
* @param statusInfo
* @param data json
* </pre>
*/
public static void processProtobufResultWithData(HttpServletResponse response,
int status, String statusInfo, String data) {
ProtobufResult.PBResult.Builder builder = ProtobufResult.PBResult
.newBuilder();
OutputStream out = null;
try {
out = response.getOutputStream();
builder.setStatus(status).setStatusInfo(statusInfo).setData(data)
.build().writeTo(out);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
try {
builder.setStatus(-1).setStatusInfo(e.getMessage()).build()
.writeTo(out);
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
}
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* <pre>
* @param response
* @param status 0 , :
* @param statusInfo
* </pre>
*/
public static void processProtobufResultWithoutData(HttpServletResponse response,
int status, String statusInfo) {
processProtobufResultWithData(response, status, statusInfo, null);
}
pbresult.proto
と書く
package tutorial;
option java_package = "org.kanpiaoxue.test.protobuf";
option java_outer_classname = "ProtobufResult";
message PBResult {
required int32 status = 1;
optional string statusInfo = 2;
optional string data = 3;
}
私たちはHTTPの相手にPOSTリクエストを開始する必要があります.また、postのパラメータはProtobufでカプセル化されます.もし操作したら?
送信元のspringmvcのControllerのコードを次に示します.
/**
*<pre>
* @param response
* @param id
* @param name
* @param email
*
* http://localhost:8080/dmap-console/web/testPb/receiveAndPOSTTestPBMessage
*</pre>
*/
@RequestMapping(value = "/receiveAndPOSTTestPBMessage",
method = { RequestMethod.POST })
public void receiveAndPOSTTestPBMessage(HttpServletResponse response,
int id, String name, String email) {
String url = createRemoteUrl(receiveAndPOSTTestPBMessageUrl);
LOGGER.debug(String.format(
"receive id:%d,name:%s,email:%s and route url[%s]", id, name,
email, url));
try {
Preconditions.checkArgument(id > 0);
Preconditions.checkArgument(!Strings.isNullOrEmpty(name));
Preconditions.checkArgument(!Strings.isNullOrEmpty(email));
PostArgsExample.Message.Builder builder = PostArgsExample.Message
.newBuilder();
byte[] args = builder.setId(id).setName(name).setEmail(email)
.build().toByteArray();
AjaxResult result = postForPBResult(restTemplate, url, args);
Tools.printToJson(result, response);
} catch (Exception e) {
e.printStackTrace();
processErrorForResponse(response, e.getMessage());
}
}
/**
* <pre>
* @param restTemplate
* @param url http
* @param args
* @return AjaxResult
* @throws InvalidProtocolBufferException
* url POST
* </pre>
*/
public static AjaxResult postForPBResult(RestTemplate restTemplate,
String url, Object args) throws InvalidProtocolBufferException {
byte[] rs = restTemplate.postForObject(url, args, byte[].class);
ProtobufResult.PBResult obj = ProtobufResult.PBResult.parseFrom(rs);
AjaxResult result = new AjaxResult();
result.setStatus(obj.getStatus());
result.setStatusInfo(obj.getStatusInfo());
return result;
}
受信者Controlのコードは次のとおりです.
/**
* <pre>
* @param response
* @param args
* </pre>
*/
@RequestMapping(value = "/receiveAndPOSTTestPBMessage",
method = { RequestMethod.POST })
public void receiveAndPOSTTestPBMessage(HttpServletResponse response,
@RequestBody byte[] args) {
LOGGER.debug("receiveAndPOSTTestPBMessage");
try {
Preconditions.checkNotNull(args, "byte[] args is null!");
PostArgsExample.Message message = PostArgsExample.Message
.parseFrom(args);
LOGGER.debug(String.format("receive message %s", message.toString()));
int status = 0;
String statusInfo = "OK";
Tools.processProtobufResultWithData(response, status, statusInfo,
message.toString());
} catch (Exception e) {
e.printStackTrace();
Tools.processProtobufResultWithoutData(response, -1, "error-test");
}
}