利用 Spring 自動(dòng)類型轉(zhuǎn)換與回調(diào)模式寫(xiě)出優(yōu)雅的代碼

關(guān)注GZH?java架構(gòu)寶典

當(dāng)我們使用 dubbo 或者 feign 進(jìn)行 RPC 調(diào)用用時(shí),通常的調(diào)用模板方式如下:

public BizResponse method(BizRequest request){

RpcRequest rpcRequest = buildRpcRequest();

RpcReponse reuslt = xxxFacade.invoke(rpcRequest);

// 判斷響應(yīng)碼與響應(yīng)對(duì)象

return buildResponse(result);

}

private RpcRequest convert(BizRequest reuest){

RpcRequest request = new RpcRequest();

// 處理過(guò)程

return request;

}

private BizResponse convert(RpcResponse response) {

BizResponse response = new BizResponse();

// 處理過(guò)程

return response:

}

其實(shí)這個(gè)一套模板處理模式,在最開(kāi)始的時(shí)候我一般會(huì)把對(duì)象轉(zhuǎn)換過(guò)程抽取到 XxxConverter 類使用靜態(tài)方法進(jìn)行處理。但是在上周寫(xiě)代碼的時(shí)候就想到可以利用 Spring 進(jìn)行依賴注入的自動(dòng)類型轉(zhuǎn)換來(lái)幫助我進(jìn)行對(duì)象轉(zhuǎn)換。

在上面的一個(gè)方法當(dāng)中涉及到兩次對(duì)象轉(zhuǎn)換:

業(yè)務(wù)對(duì)象轉(zhuǎn)換成 RPC 請(qǐng)求對(duì)象

RPC 響應(yīng)對(duì)象轉(zhuǎn)換成業(yè)務(wù)響應(yīng)對(duì)象

在這里面我們需要實(shí)現(xiàn)org.springframework.core.convert.converter.Converter接口:

BizRequestToRpcRequestConverter.java

@Component

public class BizRequestToRpcRequestConverter implements Converter {

@Override

public RpcRequest convert(BizRequest source) {

Assert.notNull(source, "source must no null");

RpcRequest request = new RpcRequest();

request.setXxx(source.getXxx());

// ....

return request;

}

}

以及:

RpcResponseToBizResponseConverter.java

@Component

public class RpcResponseToBizResponseConverter implements Converter {

@Override

public BizResponse convert(RpcResponse source) {

Assert.notNull(source, "source must no null");

BizResponse response = new BizResponse();

response.setXxx(source.getXxx());

// ....

return response;

}

}

注意這 2 個(gè)實(shí)現(xiàn)類上面需要添加 @Component 注解,這樣就可以把它們添加到 Spring 容器當(dāng)中去了。下面我們就需要把這 2 個(gè)轉(zhuǎn)換器添加到配置當(dāng)中:

ConversionServiceConfig.java

@Configuration

public class ConversionServiceConfig {

@Bean

public GenericConversionService genericConversionService(List converters){

GenericConversionService conversionService = new GenericConversionService();

converters.forEach(converter -> conversionService.addConverter(converter));

return conversionService;

}

}

因?yàn)槲覀冞M(jìn)行 Dubbo 服務(wù)調(diào)用以及結(jié)果處理的時(shí)候處理邏輯是一致的,在這里我就借鑒了一下 TransactionTemplate 的思想,基于回調(diào)方式的處理。

@Slf4j

@Service("orderClientDubbo")

public class OrderClientDubbo implements OrderClient {

@Resource

protected ConversionService genericConversionService;

@Reference

private OrderFacade orderFacade;

@Override

public BaseResponse orderApply(OrderReq request) {

log.info("OrderClientDubbo#orderApply request param is {}", JSON.toJSONString(request));

OrderApplyRequest remoteRequest = genericConversionService.convert(request, OrderApplyRequest.class);

BaseResponse response = execute(OrderRes.class,

() -> orderFacade.orderApply(remoteRequest));

log.info("OrderClientDubbo#orderApply response is {}", JSON.toJSONString(response));

return response;

}

public BaseResponse execute(Class dataClazz, InvokeCallback callback){

// 非空判斷

Assert.notNull(dataClazz, "dataClazz must not null");

// 遠(yuǎn)程調(diào)用

CommonResponse response;

try {

response = callback.doInExecute();

} catch (Exception e) {

log.error("SecurityClientDubbo invoke security service fail", e);

return BaseResponse.error(EngineErrorCodeEnum.SYSTEM_ERROR);

}

// 處理結(jié)果

return processResponse(dataClazz, response);

}

private BaseResponse processResponse(Class responseClazz, CommonResponse response) {

if(response == null) {

return BaseResponse.error(EngineErrorCodeEnum.SYSTEM_ERROR);

}

if(!SuccessCodeConstants.PAY_ENGINE_SUCCESS_CODE.equals(response.getCode())) {

return BaseResponse.error(response.getCode(), response.getMsg());

}

T result = genericConversionService.convert(response.getData(), responseClazz);

return BaseResponse.create(response.getCode(), response.getMsg(), result);

}

@FunctionalInterface

public interface InvokeCallback {

CommonResponse doInExecute();

}

}

上面就是整個(gè)代碼實(shí)現(xiàn),歸納起來(lái)需要實(shí)現(xiàn)以下幾個(gè)步驟:

定義一個(gè)類型轉(zhuǎn)換服務(wù),只需要定義一次

每一個(gè)方法對(duì)應(yīng)兩個(gè)轉(zhuǎn)換器實(shí)現(xiàn):業(yè)務(wù)請(qǐng)求對(duì)象 -> RPC 請(qǐng)求對(duì)象 以及 RPC 響應(yīng)對(duì)象 -> 業(yè)務(wù)響應(yīng)對(duì)象

遠(yuǎn)程調(diào)用方法中統(tǒng)一使用模板加回調(diào)方式

當(dāng)然這里我只在接口中定義了一個(gè)方法,方法越多越能體現(xiàn)出這樣寫(xiě)的好處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容