天天看點

基于grpc從零開始搭建一個準生産分布式應用(6) - 04 - MapStruct-proto映射

開始前必讀:​基于grpc從零開始搭建一個準生産分布式應用(0) - quickStart​​ 

大多數與java普通類轉換類型,是以這小節隻描述一些特殊的點

一、通用模闆

@Mapper
public class BaseMapper { 
    @ObjectFactory
    public ProtocolStringList createProtocolStringList(List<String> list) {
        return new LazyStringArrayList(list.size());
    }
 
    public static byte[] toByte(ByteString bytes) {
        return bytes.toByteArray();
    }
}
 
@Mapper(uses = {ByteString.class, BaseMapper.class}, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
 collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface TestMapper {
    Test toProto(TestDTO testDTO);
    TestDTO toDTO(Test test); 
}      

二、帶有Any類型的映射

message Test3 {
  map<string, string> kv = 9;
  oneof test_oneof {----------
    string one_string = 10;
    int32 one_int = 11;
  }
  google.protobuf.Any details = 15;----------
}      
@Mapper
public class BaseMapper {
 
    @ObjectFactory
    public ProtocolStringList createProtocolStringList(List<String> list) {
        return new LazyStringArrayList(list.size());
    }
 
    public static byte[] toByte(ByteString bytes) {
        return bytes.toByteArray();
    }
 
    public static ByteString copyFrom(byte[] bytes) {
        return ByteString.copyFrom(bytes);
    }
 
    // any轉javabean的中間轉換方法
    public static <T extends GeneratedMessageV3> T unpack(Any any, @TargetType Class<T> clazz) {
        T unpack;
        try {
            unpack  = any.unpack(clazz);
        } catch (InvalidProtocolBufferException e) {
            return null;
        }
        return unpack;
    }
 
    // 這裡隻是為了在mapstruct編譯找最合适方法時中間的過渡,并不是直接調用,但一定要加,具體分析參見第12.6章
    public static <T extends GeneratedMessageV3> Any pack(T message) {
        return Any.pack(message);
    }
    
    // protobuf轉javabean的中間轉換方法
    public static Any packGeneratedMessageV3(GeneratedMessageV3 message) {
        return Any.pack(message);
    }
 
    public static Date toDateFromString(String dateString, String format) {
        if (StringUtils.isEmpty(dateString)) {
            return null;
        }
        Date date;
        try {
            date = new SimpleDateFormat(format).parse(dateString);
        } catch (ParseException e) {
            return null;
        }
        return date;
    }
 
}
 
@Mapper(uses = { BaseMapper.class}, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
        collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface TestMapper {
 
    Test3 toProto(Test3DTO test3DTO);
 
    // 對象屬性的轉換一定要手動定義方法
    Item3 toProtoItem(ItemDTO itemDTO);
 
    @Mapping(target = "createTime", expression = "java(BaseMapper.toDateFromString(test.getCreateTime(), \"yyyy-mm-dd\"))")
    Test3DTO toDTO(Test3 test);
 
    // 對象屬性的轉換一定要手動定義方法
    ItemDTO toItemDTO(Item3 item3);
 
    @ValueMapping(source = "UNRECOGNIZED", target = MappingConstants.NULL)
    TypeEnum toTypeEnum(DownloadResourceTypeEnum downloadResourceTypeEnum);
 
}      

三、Date類型映射

mapstrut預設為getSeconds()這個是有問題的
Date轉化為com.google.protobuf.Timestamp
Timestamp a = Timestamps.fromMillis(new Date().getTime());

com.google.protobuf.Timestamp轉化為Date:
Timestamp timestamp = null;
Date date = new Date(timestamp.getSeconds() * 1000);