?
? ?代码:
? ?
?
class="java" name="code">package com.zhaoyou.tars.common; /** * @author: Mr_Q * @create: 2019-03-12 11:40 * @program: basic-client-test * @description: **/ public class HeaderReqVo { /*** * * "version": // 版本号 * "traceId"://贯穿始终的ID, 调用方传 * "timestamp": //自己的当前时间 * "id": 自己的服务ID * "method":com.zhaoyou.osd.service.osp.xxx //自己方法名 * "ip"://自己的IP * * */ private final String version; private final String traceId; private final String timestamp; private final String id; private final String method; private final String ip; public static HeaderInner create(){ return new HeaderInner(); } public static final class HeaderInner { private String version; private String traceId; private String timestamp; private String id; private String method; private String ip; public HeaderInner setVersion(String version) { this.version = version; return this; } public HeaderInner setTraceId(String traceId) { this.traceId = traceId; return this; } public HeaderInner setTimestamp(String timestamp) { this.timestamp = timestamp; return this; } public HeaderInner setId(String id) { this.id = id; return this; } public HeaderInner setMethod(String method) { this.method = method; return this; } public HeaderInner setIp(String ip) { this.ip = ip; return this; } public HeaderReqVo build() { return new HeaderReqVo(this); } } private HeaderReqVo(HeaderInner builder) { this.version = builder.version; this.traceId = builder.traceId; this.timestamp = builder.timestamp; this.id = builder.id; this.method = builder.method; this.ip = builder.ip; } @Override public String toString() { return "HeaderReqVo{" + "version='" + version + '\'' + ", traceId='" + traceId + '\'' + ", timestamp='" + timestamp + '\'' + ", id='" + id + '\'' + ", method='" + method + '\'' + ", ip='" + ip + '\'' + '}'; } }
?
? ?测试:
?
??
public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(()->{ HeaderReqVo getUserInfo = HeaderReqVo.create().setVersion("1.0").setTraceId("user.server").setTimestamp(String.valueOf(System.currentTimeMillis())).setId("111").setMethod("getUserInfo").setIp("127.0.0.1").build(); System.out.println(getUserInfo); }); executorService.execute(()->{ HeaderReqVo getUserInfo = HeaderReqVo.create().setVersion("2.0").setTraceId("user.server2").setTimestamp(String.valueOf(System.currentTimeMillis())).setId("222").setMethod("getUserInfo2").setIp("127.0.0.2").build(); System.out.println(getUserInfo); }); }
?
? 结果
? ?
??
? ? ? ?优点:
? ? ? ? ?(1) 继承建造者的优点,解耦
? ? ? ? ?(2) 使用链式编程,可读性好??
?
?
? ?注意点:标红部分为注意点,不然会出现多线程问题
?
?