
Photo @ Priscilla Du Preez
文 | 常意,阿里巴巴中間件
前言
古語有云:
道為術之靈,術為道之體;以道統(tǒng)術,以術得道。
1.利用語法
1.1.利用三元表達式
String title;if (isMember(phone)) {title = "會員";} else {title = "游客";}
String title = isMember(phone) ? "會員" : "游客";
1.2.利用 for-each 語句
double[] values = ...;for(int i = 0; i < values.length; i++) {double value = values[i];// TODO: 處理value}List<Double> valueList = ...;Iterator<Double> iterator = valueList.iterator();while (iterator.hasNext()) {Double value = iterator.next();// TODO: 處理value}
double[] values = ...;for(double value : values) {// TODO: 處理value}List<Double> valueList = ...;for(Double value : valueList) {// TODO: 處理value}
1.3.利用 try-with-resource 語句
BufferedReader reader = null;try {reader = new BufferedReader(new FileReader("cities.csv"));String line;while ((line = reader.readLine()) != null) {// TODO: 處理line}} catch (IOException e) {log.error("讀取文件異常", e);} finally {if (reader != null) {try {reader.close();} catch (IOException e) {log.error("關閉文件異常", e);}}}
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {String line;while ((line = reader.readLine()) != null) {// TODO: 處理line}} catch (IOException e) {log.error("讀取文件異常", e);}
1.4.利用 return 關鍵字
public static boolean hasSuper(@NonNull List<UserDO> userList) {boolean hasSuper = false;for (UserDO user : userList) {if (Boolean.TRUE.equals(user.getIsSuper())) {hasSuper = true;break;}}return hasSuper;}
public static boolean hasSuper(@NonNull List<UserDO> userList) {for (UserDO user : userList) {if (Boolean.TRUE.equals(user.getIsSuper())) {return true;}}return false;}
1.5.利用 static 關鍵字
public final class GisHelper {public double distance(double lng1, double lat1, double lng2, double lat2) {// 方法實現(xiàn)代碼}}GisHelper gisHelper = new GisHelper();double distance = gisHelper.distance(116.178692D, 39.967115D, 116.410778D, 39.899721D);
public final class GisHelper {public static double distance(double lng1, double lat1, double lng2, double lat2) {// 方法實現(xiàn)代碼}}double distance = GisHelper.distance(116.178692D, 39.967115D, 116.410778D, 39.899721D);
1.6.利用 lambda 表達式
new Thread(new Runnable() {public void run() {// 線程處理代碼}}).start();
new Thread(() -> {// 線程處理代碼}).start();
1.7.利用方法引用
Arrays.sort(nameArray, (a, b) -> a.compareToIgnoreCase(b));List<Long> userIdList = userList.stream().map(user -> user.getId()).collect(Collectors.toList());
精簡:
Arrays.sort(nameArray, String::compareToIgnoreCase);List<Long> userIdList = userList.stream().map(UserDO::getId).collect(Collectors.toList());
1.8.利用靜態(tài)導入
List<Double> areaList = radiusList.stream().map(r -> Math.PI * Math.pow(r, 2)).collect(Collectors.toList());...
import static java.lang.Math.PI;import static java.lang.Math.pow;import static java.util.stream.Collectors.toList;List<Double> areaList = radiusList.stream().map(r -> PI * pow(r, 2)).collect(toList());...
1.9.利用 unchecked 異常
@Servicepublic class UserService {public void createUser(UserCreateVO create, OpUserVO user) throws BusinessException {checkOperatorUser(user);...}private void checkOperatorUser(OpUserVO user) throws BusinessException {if (!hasPermission(user)) {throw new BusinessException("用戶無操作權限");}...}...}@RestController@RequestMapping("/user")public class UserController {@Autowiredprivate UserService userService;@PostMapping("/createUser")public Result<Void> createUser(@RequestBody @Valid UserCreateVO create, OpUserVO user) throws BusinessException {userService.createUser(create, user);return Result.success();}...}
@Servicepublic class UserService {public void createUser(UserCreateVO create, OpUserVO user) {checkOperatorUser(user);...}private void checkOperatorUser(OpUserVO user) {if (!hasPermission(user)) {throw new BusinessRuntimeException("用戶無操作權限");}...}...}@RestController@RequestMapping("/user")public class UserController {@Autowiredprivate UserService userService;@PostMapping("/createUser")public Result<Void> createUser(@RequestBody @Valid UserCreateVO create, OpUserVO user) {userService.createUser(create, user);return Result.success();}...}
2.利用注解
2.1.利用 Lombok 注解
public class UserVO {private Long id;private String name;public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}...}
@Getter@Setter@ToStringpublic class UserVO {private Long id;private String name;...}
2.2.利用 Validation 注解
@Getter@Setter@ToStringpublic class UserCreateVO { @NotBlank(message = "用戶名稱不能為空") private String name; @NotNull(message = "公司標識不能為空") private Long companyId; ...}@Service@Validatedpublic class UserService { public Long createUser(@Valid UserCreateVO create) { // TODO: 創(chuàng)建用戶 return null; }}
@Getter@Setter@ToStringpublic class UserCreateVO {@NotBlank(message = "用戶名稱不能為空")private String name;@NotNull(message = "公司標識不能為空")private Long companyId;...}@Service@Validatedpublic class UserService {public Long createUser(@Valid UserCreateVO create) {// TODO: 創(chuàng)建用戶return null;}}
2.3.利用 @NonNull 注解
public List<UserVO> queryCompanyUser(Long companyId) {// 檢查公司標識if (companyId == null) {return null;}// 查詢返回用戶List<UserDO> userList = userDAO.queryByCompanyId(companyId);return userList.stream().map(this::transUser).collect(Collectors.toList());}Long companyId = 1L;List<UserVO> userList = queryCompanyUser(companyId);if (CollectionUtils.isNotEmpty(userList)) {for (UserVO user : userList) {// TODO: 處理公司用戶}}
public @NonNull List<UserVO> queryCompanyUser(@NonNull Long companyId) {List<UserDO> userList = userDAO.queryByCompanyId(companyId);return userList.stream().map(this::transUser).collect(Collectors.toList());}Long companyId = 1L;List<UserVO> userList = queryCompanyUser(companyId);for (UserVO user : userList) {// TODO: 處理公司用戶}
2.4.利用注解特性
;
3.利用泛型
3.1.泛型接口
在 Java 沒有引入泛型前,都是采用 Object 表示通用對象,最大的問題就是類型無法強校驗并且需要強制類型轉換。
public interface Comparable {public int compareTo(Object other);}@Getter@Setter@ToStringpublic class UserVO implements Comparable {private Long id;@Overridepublic int compareTo(Object other) {UserVO user = (UserVO)other;return Long.compare(this.id, user.id);}}
public interface Comparable<T> {public int compareTo(T other);}@Getter@Setter@ToStringpublic class UserVO implements Comparable<UserVO> {private Long id;@Overridepublic int compareTo(UserVO other) {return Long.compare(this.id, other.id);}}
3.2.泛型類
@Getter@Setter@ToStringpublic class IntPoint {private Integer x;private Integer y;}@Getter@Setter@ToStringpublic class DoublePoint {private Double x;private Double y;}
@Getter@Setter@ToStringpublic class Point<T extends Number> {private T x;private T y;}
3.3.泛型方法
public static Map<String, Integer> newHashMap(String[] keys, Integer[] values) {// 檢查參數(shù)非空if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {return Collections.emptyMap();}// 轉化哈希映射Map<String, Integer> map = new HashMap<>();int length = Math.min(keys.length, values.length);for (int i = 0; i < length; i++) {map.put(keys[i], values[i]);}return map;}...
public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {// 檢查參數(shù)非空if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {return Collections.emptyMap();}// 轉化哈希映射Map<K, V> map = new HashMap<>();int length = Math.min(keys.length, values.length);for (int i = 0; i < length; i++) {map.put(keys[i], values[i]);}return map;}
4.利用自身方法
4.1.利用構造方法
@Getter@Setter@ToStringpublic class PageDataVO<T> {private Long totalCount;private List<T> dataList;}PageDataVO<UserVO> pageData = new PageDataVO<>();pageData.setTotalCount(totalCount);pageData.setDataList(userList);return pageData;
@Getter@Setter@ToString@NoArgsConstructor@AllArgsConstructorpublic class PageDataVO<T> {private Long totalCount;private List<T> dataList;}return new PageDataVO<>(totalCount, userList);
4.2.利用 Set 的 add 方法
Set<Long> userIdSet = new HashSet<>();List<UserVO> userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {if (!userIdSet.contains(userDO.getId())) {userIdSet.add(userDO.getId());userVOList.add(transUser(userDO));}}
SSet<Long> userIdSet = new HashSet<>();List<UserVO> userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {if (userIdSet.add(userDO.getId())) {userVOList.add(transUser(userDO));}}
4.3.利用 Map 的 computeIfAbsent 方法
Map<Long, List<UserDO>> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {Long roleId = userDO.getRoleId();List<UserDO> userList = roleUserMap.get(roleId);if (Objects.isNull(userList)) {userList = new ArrayList<>();roleUserMap.put(roleId, userList);}userList.add(userDO);}
Map<Long, List<UserDO>> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {roleUserMap.computeIfAbsent(userDO.getRoleId(), key -> new ArrayList<>()).add(userDO);}
4.4.利用鏈式編程
StringBuilder builder = new StringBuilder(96);builder.append("select id, name from ");builder.append(T_USER);builder.append(" where id = ");builder.append(userId);builder.append(";");
StringBuilder builder = new StringBuilder(96);builder.append("select id, name from ").append(T_USER).append(" where id = ").append(userId).append(";");
5.利用工具方法
5.1.避免空值判斷
if (userList != null && !userList.isEmpty()) {// TODO: 處理代碼}
if (CollectionUtils.isNotEmpty(userList)) {// TODO: 處理代碼}
5.2.避免條件判斷
double result;if (value <= MIN_LIMIT) {result = MIN_LIMIT;} else {result = value;}
double result = Math.max(MIN_LIMIT, value);
5.3.簡化賦值語句
public static final List<String> ANIMAL_LIST;static {List<String> animalList = new ArrayList<>();animalList.add("dog");animalList.add("cat");animalList.add("tiger");ANIMAL_LIST = Collections.unmodifiableList(animalList);}
// JDK流派public static final List<String> ANIMAL_LIST = Arrays.asList("dog", "cat", "tiger");// Guava流派public static final List<String> ANIMAL_LIST = ImmutableList.of("dog", "cat", "tiger");
5.4.簡化數(shù)據(jù)拷貝
UserVO userVO = new UserVO();userVO.setId(userDO.getId());userVO.setName(userDO.getName());...userVO.setDescription(userDO.getDescription());userVOList.add(userVO);
UserVO userVO = new UserVO();BeanUtils.copyProperties(userDO, userVO);userVOList.add(userVO);
List<UserVO> userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);
精簡代碼,但不能以過大的性能損失為代價。例子是淺層拷貝,用不著 JSON 這樣重量級的武器。
5.5.簡化異常斷言
if (Objects.isNull(userId)) {throw new IllegalArgumentException("用戶標識不能為空");}
Assert.notNull(userId, "用戶標識不能為空");
5.6.簡化測試用例
@Testpublic void testCreateUser() {UserCreateVO userCreate = new UserCreateVO();userCreate.setName("Changyi");userCreate.setTitle("Developer");userCreate.setCompany("AMAP");...Long userId = userService.createUser(OPERATOR, userCreate);Assert.assertNotNull(userId, "創(chuàng)建用戶失敗");}
精簡:
@Testpublic void testCreateUser() {String jsonText = ResourceHelper.getResourceAsString(getClass(), "createUser.json");UserCreateVO userCreate = JSON.parseObject(jsonText, UserCreateVO.class);Long userId = userService.createUser(OPERATOR, userCreate);Assert.assertNotNull(userId, "創(chuàng)建用戶失敗");}
5.7.簡化算法實現(xiàn)
int totalSize = valueList.size();List<List<Integer>> partitionList = new ArrayList<>();for (int i = 0; i < totalSize; i += PARTITION_SIZE) {partitionList.add(valueList.subList(i, Math.min(i + PARTITION_SIZE, totalSize)));}
精簡:
List<List<Integer>> partitionList = ListUtils.partition(valueList, PARTITION_SIZE);
5.8.封裝工具方法
// 設置參數(shù)值if (Objects.nonNull(user.getId())) {statement.setLong(1, user.getId());} else {statement.setNull(1, Types.BIGINT);}...
/** SQL輔助類 */public final class SqlHelper {/** 設置長整數(shù)值 */public static void setLong(PreparedStatement statement, int index, Long value) throws SQLException {if (Objects.nonNull(value)) {statement.setLong(index, value.longValue());} else {statement.setNull(index, Types.BIGINT);}}...}// 設置參數(shù)值SqlHelper.setLong(statement, 1, user.getId());
6.利用數(shù)據(jù)結構
6.1.利用數(shù)組簡化
public static int getGrade(double score) {if (score >= 90.0D) {return 1;}if (score >= 80.0D) {return 2;}if (score >= 60.0D) {return 3;}if (score >= 30.0D) {return 4;}return 5;}
private static final double[] SCORE_RANGES = new double[] {90.0D, 80.0D, 60.0D, 30.0D};public static int getGrade(double score) {for (int i = 0; i < SCORE_RANGES.length; i++) {if (score >= SCORE_RANGES[i]) {return i + 1;}}return SCORE_RANGES.length + 1;}
6.2.利用 Map 簡化
public static String getBiologyClass(String name) {switch (name) {case "dog" :return "animal";case "cat" :return "animal";case "lavender" :return "plant";...default :return null;}}
精簡:
private static final Map<String, String> BIOLOGY_CLASS_MAP= ImmutableMap.<String, String>builder().put("dog", "animal").put("cat", "animal").put("lavender", "plant")....build();public static String getBiologyClass(String name) {return BIOLOGY_CLASS_MAP.get(name);}
6.3.利用容器類簡化
@Setter@Getter@ToString@AllArgsConstructorpublic static class PointAndDistance {private Point point;private Double distance;}public static PointAndDistance getNearest(Point point, Point[] points) {// 計算最近點和距離...// 返回最近點和距離return new PointAndDistance(nearestPoint, nearestDistance);}
public static Pair<Point, Double> getNearest(Point point, Point[] points) {// 計算最近點和距離...// 返回最近點和距離return ImmutablePair.of(nearestPoint, nearestDistance);}
6.4.利用 ThreadLocal 簡化
public static String formatDate(Date date, DateFormat format) {return format.format(date);}public static List<String> getDateList(Date minDate, Date maxDate, DateFormat format) {List<String> dateList = new ArrayList<>();Calendar calendar = Calendar.getInstance();calendar.setTime(minDate);String currDate = formatDate(calendar.getTime(), format);String maxsDate = formatDate(maxDate, format);while (currDate.compareTo(maxsDate) <= 0) {dateList.add(currDate);calendar.add(Calendar.DATE, 1);currDate = formatDate(calendar.getTime(), format);}return dateList;}
精簡:
private static final ThreadLocal<DateFormat> LOCAL_DATE_FORMAT = new ThreadLocal<DateFormat>() {@Overrideprotected DateFormat initialValue() {return new SimpleDateFormat("yyyyMMdd");}};public static String formatDate(Date date) {return LOCAL_DATE_FORMAT.get().format(date);}public static List<String> getDateList(Date minDate, Date maxDate) {List<String> dateList = new ArrayList<>();Calendar calendar = Calendar.getInstance();calendar.setTime(minDate);String currDate = formatDate(calendar.getTime());String maxsDate = formatDate(maxDate);while (currDate.compareTo(maxsDate) <= 0) {dateList.add(currDate);calendar.add(Calendar.DATE, 1);currDate = formatDate(calendar.getTime());}return dateList;}
7.利用 Optional
7.1.保證值存在
Integer thisValue;if (Objects.nonNull(value)) {thisValue = value;} else {thisValue = DEFAULT_VALUE;}
Integer thisValue = Optional.ofNullable(value).orElse(DEFAULT_VALUE);
7.2.保證值合法
Integer thisValue;if (Objects.nonNull(value) && value.compareTo(MAX_VALUE) <= 0) {thisValue = value;} else {thisValue = MAX_VALUE;}
精簡:
Integer thisValue = Optional.ofNullable(value).filter(tempValue -> tempValue.compareTo(MAX_VALUE) <= 0).orElse(MAX_VALUE);
7.3.避免空判斷
String zipcode = null;if (Objects.nonNull(user)) {Address address = user.getAddress();if (Objects.nonNull(address)) {Country country = address.getCountry();if (Objects.nonNull(country)) {zipcode = country.getZipcode();}}}
精簡:
tring zipcode = Optional.ofNullable(user).map(User::getAddress).map(Address::getCountry).map(Country::getZipcode).orElse(null);
8.利用 Stream
流(Stream)是Java 8的新成員,允許你以聲明式處理數(shù)據(jù)集合,可以看成為一個遍歷數(shù)據(jù)集的高級迭代器。流主要有三部分構成:獲取一個數(shù)據(jù)源→數(shù)據(jù)轉換→執(zhí)行操作獲取想要的結果。每次轉換原有 Stream 對象不改變,返回一個新的 Stream 對象,這就允許對其操作可以像鏈條一樣排列,形成了一個管道。流(Stream)提供的功能非常有用,主要包括匹配、過濾、匯總、轉化、分組、分組匯總等功能。
8.1.匹配集合數(shù)據(jù)
boolean isFound = false;for (UserDO user : userList) {if (Objects.equals(user.getId(), userId)) {isFound = true;break;}}
精簡:
boolean isFound = userList.stream().anyMatch(user -> Objects.equals(user.getId(), userId));
8.2.過濾集合數(shù)據(jù)
List<UserDO> resultList = new ArrayList<>();for (UserDO user : userList) {if (Boolean.TRUE.equals(user.getIsSuper())) {resultList.add(user);}}
精簡:
List<UserDO> resultList = userList.stream().filter(user -> Boolean.TRUE.equals(user.getIsSuper())).collect(Collectors.toList());
8.3.匯總集合數(shù)據(jù)
double total = 0.0D;for (Account account : accountList) {total += account.getBalance();}
精簡:
double total = accountList.stream().mapToDouble(Account::getBalance).sum();
8.4.轉化集合數(shù)據(jù)
普通:
List<UserVO> userVOList = new ArrayList<>();for (UserDO userDO : userDOList) {userVOList.add(transUser(userDO));}
精簡:
List<UserVO> userVOList = userDOList.stream().map(this::transUser).collect(Collectors.toList());
8.5.分組集合數(shù)據(jù)
Map<Long, List<UserDO>> roleUserMap = new HashMap<>();for (UserDO userDO : userDOList) {roleUserMap.computeIfAbsent(userDO.getRoleId(), key -> new ArrayList<>()).add(userDO);}
精簡:
Map<Long, List<UserDO>> roleUserMap = userDOList.stream().collect(Collectors.groupingBy(UserDO::getRoleId));
8.6.分組匯總集合
Map<Long, Double> roleTotalMap = new HashMap<>();for (Account account : accountList) {Long roleId = account.getRoleId();Double total = Optional.ofNullable(roleTotalMap.get(roleId)).orElse(0.0D);roleTotalMap.put(roleId, total + account.getBalance());}
精簡:
roleTotalMap = accountList.stream().collect(Collectors.groupingBy(Account::getRoleId, Collectors.summingDouble(Account::getBalance)));
8.7.生成范圍集合
int[] array1 = new int[N];for (int i = 0; i < N; i++) {array1[i] = i + 1;}int[] array2 = new int[N];array2[0] = 1;for (int i = 1; i < N; i++) {array2[i] = array2[i - 1] * 2;}
精簡:
int[] array1 = IntStream.rangeClosed(1, N).toArray();int[] array2 = IntStream.iterate(1, n -> n * 2).limit(N).toArray();
9.利用程序結構
9.1.返回條件表達式
public boolean isSuper(Long userId)UserDO user = userDAO.get(userId);if (Objects.nonNull(user) && Boolean.TRUE.equals(user.getIsSuper())) {return true;}return false;}
精簡:
public boolean isSuper(Long userId)UserDO user = userDAO.get(userId);return Objects.nonNull(user) && Boolean.TRUE.equals(user.getIsSuper());}
9.2.最小化條件作用域
Result result = summaryService.reportWorkDaily(workDaily);if (result.isSuccess()) {String message = "上報工作日報成功";dingtalkService.sendMessage(user.getPhone(), message);} else {String message = "上報工作日報失敗:" + result.getMessage();log.warn(message);dingtalkService.sendMessage(user.getPhone(), message);}
精簡:
String message;Result result = summaryService.reportWorkDaily(workDaily);if (result.isSuccess()) {message = "上報工作日報成功";} else {message = "上報工作日報失敗:" + result.getMessage();log.warn(message);}dingtalkService.sendMessage(user.getPhone(), message);
9.3.調整表達式位置
String line = readLine();while (Objects.nonNull(line)) {... // 處理邏輯代碼line = readLine();}
普通2:
for (String line = readLine(); Objects.nonNull(line); line = readLine()) {... // 處理邏輯代碼}
精簡:
String line;while (Objects.nonNull(line = readLine())) {... // 處理邏輯代碼}
注意:有些規(guī)范可能不建議這種精簡寫法。
9.4.利用非空對象
private static final int MAX_VALUE = 1000;boolean isMax = (value != null && value.equals(MAX_VALUE));boolean isTrue = (result != null && result.equals(Boolean.TRUE));
private static final Integer MAX_VALUE = 1000;boolean isMax = MAX_VALUE.equals(value);boolean isTrue = Boolean.TRUE.equals(result);
10.利用設計模式
10.1.模板方法模式
@Repositorypublic class UserValue {/** 值操作 */@Resource(name = "stringRedisTemplate")private ValueOperations<String, String> valueOperations;/** 值模式 */private static final String KEY_FORMAT = "Value:User:%s";/** 設置值 */public void set(Long id, UserDO value) {String key = String.format(KEY_FORMAT, id);valueOperations.set(key, JSON.toJSONString(value));}/** 獲取值 */public UserDO get(Long id) {String key = String.format(KEY_FORMAT, id);String value = valueOperations.get(key);return JSON.parseObject(value, UserDO.class);}...}@Repositorypublic class RoleValue {/** 值操作 */@Resource(name = "stringRedisTemplate")private ValueOperations<String, String> valueOperations;/** 值模式 */private static final String KEY_FORMAT = "Value:Role:%s";/** 設置值 */public void set(Long id, RoleDO value) {String key = String.format(KEY_FORMAT, id);valueOperations.set(key, JSON.toJSONString(value));}/** 獲取值 */public RoleDO get(Long id) {String key = String.format(KEY_FORMAT, id);String value = valueOperations.get(key);return JSON.parseObject(value, RoleDO.class);}...}
精簡:
public abstract class AbstractDynamicValue<I, V> {/** 值操作 */@Resource(name = "stringRedisTemplate")private ValueOperations<String, String> valueOperations;/** 設置值 */public void set(I id, V value) {valueOperations.set(getKey(id), JSON.toJSONString(value));}/** 獲取值 */public V get(I id) {return JSON.parseObject(valueOperations.get(getKey(id)), getValueClass());}.../** 獲取主鍵 */protected abstract String getKey(I id);/** 獲取值類 */protected abstract Class<V> getValueClass();}@Repositorypublic class UserValue extends AbstractValue<Long, UserDO> {/** 獲取主鍵 */@Overrideprotected String getKey(Long id) {return String.format("Value:User:%s", id);}/** 獲取值類 */@Overrideprotected Class<UserDO> getValueClass() {return UserDO.class;}}@Repositorypublic class RoleValue extends AbstractValue<Long, RoleDO> {/** 獲取主鍵 */@Overrideprotected String getKey(Long id) {return String.format("Value:Role:%s", id);}/** 獲取值類 */@Overrideprotected Class<RoleDO> getValueClass() {return RoleDO.class;}}
10.2.建造者模式
public interface DataHandler<T> {/** 解析數(shù)據(jù) */public T parseData(Record record);/** 存儲數(shù)據(jù) */public boolean storeData(List<T> dataList);}public <T> long executeFetch(String tableName, int batchSize, DataHandler<T> dataHandler) throws Exception {// 構建下載會話DownloadSession session = buildSession(tableName);// 獲取數(shù)據(jù)數(shù)量long recordCount = session.getRecordCount();if (recordCount == 0) {return 0;}// 進行數(shù)據(jù)讀取long fetchCount = 0L;try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) {// 依次讀取數(shù)據(jù)Record record;List<T> dataList = new ArrayList<>(batchSize);while ((record = reader.read()) != null) {// 解析添加數(shù)據(jù)T data = dataHandler.parseData(record);if (Objects.nonNull(data)) {dataList.add(data);}// 批量存儲數(shù)據(jù)if (dataList.size() == batchSize) {boolean isContinue = dataHandler.storeData(dataList);fetchCount += batchSize;dataList.clear();if (!isContinue) {break;}}}// 存儲剩余數(shù)據(jù)if (CollectionUtils.isNotEmpty(dataList)) {dataHandler.storeData(dataList);fetchCount += dataList.size();dataList.clear();}}// 返回獲取數(shù)量return fetchCount;}// 使用案例long fetchCount = odpsService.executeFetch("user", 5000, new DataHandler() {/** 解析數(shù)據(jù) */public T parseData(Record record) {UserDO user = new UserDO();user.setId(record.getBigint("id"));user.setName(record.getString("name"));return user;}/** 存儲數(shù)據(jù) */public boolean storeData(List<T> dataList) {userDAO.batchInsert(dataList);return true;}});
public <T> long executeFetch(String tableName, int batchSize, Function<Record, T> dataParser, Function<List<T>, Boolean> dataStorage) throws Exception {// 構建下載會話DownloadSession session = buildSession(tableName);// 獲取數(shù)據(jù)數(shù)量long recordCount = session.getRecordCount();if (recordCount == 0) {return 0;}// 進行數(shù)據(jù)讀取long fetchCount = 0L;try (RecordReader reader = session.openRecordReader(0L, recordCount, true)) {// 依次讀取數(shù)據(jù)Record record;List<T> dataList = new ArrayList<>(batchSize);while ((record = reader.read()) != null) {// 解析添加數(shù)據(jù)T data = dataParser.apply(record);if (Objects.nonNull(data)) {dataList.add(data);}// 批量存儲數(shù)據(jù)if (dataList.size() == batchSize) {Boolean isContinue = dataStorage.apply(dataList);fetchCount += batchSize;dataList.clear();if (!Boolean.TRUE.equals(isContinue)) {break;}}}// 存儲剩余數(shù)據(jù)if (CollectionUtils.isNotEmpty(dataList)) {dataStorage.apply(dataList);fetchCount += dataList.size();dataList.clear();}}// 返回獲取數(shù)量return fetchCount;}// 使用案例long fetchCount = odpsService.executeFetch("user", 5000, record -> {UserDO user = new UserDO();user.setId(record.getBigint("id"));user.setName(record.getString("name"));return user;}, dataList -> {userDAO.batchInsert(dataList);return true;});
10.3.代理模式
@Slf4j@RestController@RequestMapping("/user")public class UserController {/** 用戶服務 */@Autowiredprivate UserService userService;/** 查詢用戶 */@PostMapping("/queryUser")public Result<?> queryUser(@RequestBody @Valid UserQueryVO query) {try {PageDataVO<UserVO> pageData = userService.queryUser(query);return Result.success(pageData);} catch (Exception e) {log.error(e.getMessage(), e);return Result.failure(e.getMessage());}}...}
@RestController@RequestMapping("/user")public class UserController {/** 用戶服務 */@Autowiredprivate UserService userService;/** 查詢用戶 */@PostMapping("/queryUser")public Result<PageDataVO<UserVO>> queryUser(@RequestBody @Valid UserQueryVO query) {PageDataVO<UserVO> pageData = userService.queryUser(query);return Result.success(pageData);}...}@Slf4j@ControllerAdvicepublic class GlobalControllerAdvice {/** 處理異常 */@ResponseBody@ExceptionHandler(Exception.class)public Result<Void> handleException(Exception e) {log.error(e.getMessage(), e);return Result.failure(e.getMessage());}}
// UserController代碼同"精簡1"@Slf4j@Aspectpublic class WebExceptionAspect {/** 點切面 */@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")private void webPointcut() {}/** 處理異常 */@AfterThrowing(pointcut = "webPointcut()", throwing = "e")public void handleException(Exception e) {Result<Void> result = Result.failure(e.getMessage());writeContent(JSON.toJSONString(result));}...}
11.利用刪除代碼
“少即是多”,“少”不是空白而是精簡,“多”不是擁擠而是完美。刪除多余的代碼,才能使代碼更精簡更完美。
11.1.刪除已廢棄的代碼
import lombok.extern.slf4j.Slf4j;@Slf4j@Servicepublic class ProductService {@Value("discardRate")private double discardRate;...private ProductVO transProductDO(ProductDO productDO) {ProductVO productVO = new ProductVO();BeanUtils.copyProperties(productDO, productVO);// productVO.setPrice(getDiscardPrice(productDO.getPrice()));return productVO;}private BigDecimal getDiscardPrice(BigDecimal originalPrice) {...}}
@Servicepublic class ProductService {...private ProductVO transProductDO(ProductDO productDO) {ProductVO productVO = new ProductVO();BeanUtils.copyProperties(productDO, productVO);return productVO;}}11.2.刪除接口方法的public對于接口(interface),所有的字段和方法都是public的,可以不用顯式聲明為public。普通:public interface UserDAO {public Long countUser(@Param("query") UserQuery query);public List<UserDO> queryUser(@Param("query") UserQuery query);}
11.2.刪除接口方法的public
public interface UserDAO {public Long countUser( UserQuery query);public List<UserDO> queryUser( UserQuery query);}
public interface UserDAO {Long countUser(@Param("query") UserQuery query);List<UserDO> queryUser(@Param("query") UserQuery query);}
11.3.刪除枚舉構造方法的 private
public enum UserStatus {DISABLED(0, "禁用"),ENABLED(1, "啟用");private final Integer value;private final String desc;private UserStatus(Integer value, String desc) {this.value = value;this.desc = desc;}...}
public enum UserStatus {DISABLED(0, "禁用"),ENABLED(1, "啟用");private final Integer value;private final String desc;UserStatus(Integer value, String desc) {this.value = value;this.desc = desc;}...}
11.4.刪除 final 類方法的 final
public final Rectangle implements Shape {...@Overridepublic final double getArea() {return width * height;}}
public final Rectangle implements Shape {...@Overridepublic double getArea() {return width * height;}}
11.5.刪除基類 implements 的接口
public interface Shape {...double getArea();}public abstract AbstractShape implements Shape {...}public final Rectangle extends AbstractShape implements Shape {...@Overridepublic double getArea() {return width * height;}}
...public final Rectangle extends AbstractShape {...@Overridepublic double getArea() {return width * height;}}
11.6.刪除不必要的變量
public Boolean existsUser(Long userId) {Boolean exists = userDAO.exists(userId);return exists;}
public Boolean existsUser(Long userId) {return userDAO.exists(userId);}
后記
古語又云:
有道無術,術尚可求也;有術無道,止于術。
陳昌毅,花名常意,地圖技術專家。
特別推薦一個分享架構+算法的優(yōu)質內容,還沒關注的小伙伴,可以長按關注一下:
長按訂閱更多精彩▼
如有收獲,點個在看,誠摯感謝
免責聲明:本文內容由21ic獲得授權后發(fā)布,版權歸原作者所有,本平臺僅提供信息存儲服務。文章僅代表作者個人觀點,不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!





