开始前必读:基于grpc从零开始搭建一个准生产分布式应用(0) - quickStart
前面章节的GRPC内基本是一个空实现,本章就实现下service业务逻辑层代码,因例子比较简单代码量也不算大,本章代码任务:1、用spring实现服务层,熟悉各注解的使用;2、实现一个VO逻辑,巩固mapStruct框架的使用。
一、工程结构
本章只涉及【base-grpc-framework-core】工程的改动,需改动的代码如下图所示:
二、创建必要的实体类
2.1、MVC层VO类
package com.zd.baseframework.core.controller.core.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class SystemLogVo {
private Long id;
private String bizId;
private Long userId;
private String trackUid;
private String code;
private String customCode;
private Integer state;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private LocalDateTime ctime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private LocalDateTime utime;
}
2.2、Service层BO类
package com.zd.baseframework.core.core.systemlog.model;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class SystemLogBo {
private Long id;
private String bizId;
private Long userId;
private String trackUid;
private String code;
private String customCode;
private Integer state;
private LocalDateTime ctime;
private LocalDateTime utime;
}
package com.zd.baseframework.core.core.systemlog.model;
import lombok.Data;
@Data
public class SystemLogQueryBo {
private String bizId;
private Long userId;
private String code;
}
2.3、VO和BO的专换工具类
新增代码第16~20行,转换VO和BO
/**
* @Title: com.zd.baseframework.core.controller.core.translator.SystemLogTranslator
* @Description http层与grpc层对象转换工具
* @author liudong
* @date 2022/6/15 8:52 PM
*/
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
imports = {MapStructMapperUtil.class},
uses = BaseMapStructMapper.class)
public interface SystemLogTranslator {
SystemLogTranslator INSTANCE = Mappers.getMapper(SystemLogTranslator.class);
/*查询请求参数转换*/
ListSystemLogRequest toGrpcQueryReqObject(SystemLogQueryRequest var);
/*查询返回结果转换,这两个是一组,其中在生成源码时toQueryResultVos会调用toQueryResultVo*/
SystemLogVo toQueryResultVo(SystemLogDto var);
List<SystemLogVo> toQueryResultVos(List<SystemLogDto> var);
}
/**
* @Title: com.zd.baseframework.core.core.systemlog.api.SystemLogDtoTranslator
* @Description grpc与service层对象转换工具类
* @author liudong
* @date 2022/6/15 8:59 PM
*/
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
imports = {MapStructMapperUtil.class},
uses = BaseMapStructMapper.class)
public interface SystemLogDtoTranslator {
SystemLogDtoTranslator INSTANCE = Mappers.getMapper(SystemLogDtoTranslator.class);
/*查询请求参数转换*/
SystemLogQueryBo toQueryBo(ListSystemLogRequest var);
/*返回结果转换*/
SystemLogDto toQueryResultDto(SystemLogBo var);
List<SystemLogDto> toQueryResultDtos(List<SystemLogBo> var);
}
三、创建Service接口和实现
3.1、接口定义
package com.zd.baseframework.core.core.systemlog.service;
public interface ISystemLogServcie {
boolean createSystemLog(SystemLogBo systemLogBo);
List<SystemLogBo> listByCondition(SystemLogQueryBo systemLogQueryBo);
}
3.2、接口实现
package com.zd.baseframework.core.core.systemlog.service.impl;
@Service
@Slf4j
@Primary
public class SystemLogServcieImpl implements ISystemLogServcie {
@Override
public boolean createSystemLog(SystemLogBo systemLogBo) {
String trackLog = LogGenerator.trackLog();
log.info(trackLog
+ "createSystemLog=" + JSONUtil.toJsonStr(systemLogBo)
);
try{
return null;
}catch(Exception e){
throw e;
}
}
@Override
public List<SystemLogBo> listByCondition(SystemLogQueryBo systemLogQueryBo) {
String trackLog = LogGenerator.trackLog();
try{
return null;
}catch(Exception e){
throw e;
}
}
}
四、建立GRPC与SERVICE调用关系
4.1、Contoller集成VO
修改com.zd.baseframework.core.controller.core.SystemLogController类的如下方法,新增第5~8行。
@PostMapping("/v1/list_systemlog")
public BaseResponse listSystemLog(@RequestBody SystemLogQueryRequest systemLogRequest){
try{
//构建查询参数
ListSystemLogRequest listSystemLogRequest = SystemLogTranslator.INSTANCE.toGrpcQueryReqObject(systemLogRequest);
ListSystemLogResponse listSystemLogResponse = iSysRecordServiceBlockingStub.listSystemLogByCondition(listSystemLogRequest);
List<SystemLogVo> vos = SystemLogTranslator.INSTANCE.toQueryResultVos(listSystemLogResponse.getDataList());
return BaseResponse.success(vos);
}catch(StatusRuntimeException e){
log.error("ErrorCode : " + e.getStatus().getCode());
return BaseResponse.error(e.getMessage());
}catch(Exception e){
e.printStackTrace();
return BaseResponse.error(e.getMessage());
}
}
4.2、Grpc调用Service逻辑
修改com.zd.baseframework.core.core.systemlog.api.impl.SystemLogServiceApiImpl类,完整代码如下:
@GrpcService
@Slf4j
public class SystemLogServiceApiImpl extends ISystemLogServiceGrpc.ISystemLogServiceImplBase {
@Autowired
private ISystemLogServcie iSystemLogServcie;
@Override
public void createSystemLog(CreateSystemLogRequest request, StreamObserver<SystemLogOperatorResponse> responseObserver) {
String bizId = request.hasBizId()?request.getBizId().getValue():null;
Long userId = request.hasUserId()?request.getUserId().getValue():null;
String code = request.hasCode()?request.getCode().getValue():null;
String customCode = request.hasCustomCode()?request.getCustomCode().getValue():null;
String trackLog = LogGenerator.trackLog();
try{
//打印原始入参
log.info(trackLog
+ " grpcReqParam=" + JsonFormat.printer().omittingInsignificantWhitespace().print(request)
);
//入参验证
if(StrUtil.isEmpty(bizId)
|| null==userId
|| StrUtil.isEmpty(code) ){
throw new AppException("非法参数");
}
SystemLogBo systemLogBo = new SystemLogBo();
systemLogBo.setCode(code);
systemLogBo.setCustomCode(customCode);
systemLogBo.setBizId(bizId);
systemLogBo.setUserId(userId);
systemLogBo.setTrackUid("10000");
boolean result = iSystemLogServcie.createSystemLog(systemLogBo);
if(result){
SystemLogOperatorResponse response = SystemLogOperatorResponse.newBuilder()
.setStatus(ResponseConst.SUCCESS)
.setMessage(ResponseConst.Msg.SUCCESS)
.build();
responseObserver.onNext(response);
}else{
log.info(trackLog
+ " grpcReqParam=" + JsonFormat.printer().omittingInsignificantWhitespace().print(request)
+ " result=fail" );
responseObserver.onError(Status.INVALID_ARGUMENT.asException());
}
responseObserver.onCompleted();
}catch (AppException e) {
log.error(e.getMessage());
responseObserver.onError(Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asException());
}
catch(Exception e){
log.error(e.getMessage());
responseObserver.onError(Status.INTERNAL.withDescription(e.getMessage()).asException());
}
}
@Override
public void listSystemLogByCondition(ListSystemLogRequest request, StreamObserver<ListSystemLogResponse> responseObserver) {
String trackLog = LogGenerator.trackLog();
try{
//打印原始入参
log.info(trackLog
+ " grpcReqParam=" + JsonFormat.printer().omittingInsignificantWhitespace().print(request)
);
SystemLogQueryBo systemLogQueryBo = SystemLogDtoTranslator.INSTANCE.toQueryBo(request);
List<SystemLogBo> systemLogBoList = iSystemLogServcie.listByCondition(systemLogQueryBo);
log.info(trackLog
+ " systemLogBoListSize=" + CollUtil.size(systemLogBoList));
List<SystemLogDto> dtos = SystemLogDtoTranslator.INSTANCE.toQueryResultDtos(systemLogBoList);
ListSystemLogResponse response = ListSystemLogResponse.newBuilder().addAllData(dtos).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}catch (AppException e) {
log.error(e.getMessage());
responseObserver.onError(Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asException());
}
catch(Exception e){
log.error(e.getMessage());
responseObserver.onError(Status.INTERNAL.withDescription(e.getMessage()).asException());
}
}
}