Java8 函数式编程实战
业务场景
前端传递当前商户下一个或多个配置的key,从服务器获取每个key对应的数据。
请求:
var url = http:
响应:
{
"shop":[],
"paymentType":[],
"user":[],
"userLevel":[]
}
部分核心代码
@Service
public class MetadataServiceImpl {
private Map<String, Function<Long, Object>> metaFunMap = new HashMap<>();
@Autowired
public MetadataServiceImpl() {
metaFunMap.put("shop", this::getShop);
metaFunMap.put("paymentType", this::getPaymentType);
metaFunMap.put("user", this::getUser);
metaFunMap.put("userLevel", this::getUserLevel);
}
private List<Shop> getShop(Long merchantId){
return null;
}
private List<PaymentType> getPaymentType(Long merchantId){
return null;
}
private List<User> getUser(Long merchantId){
return null;
}
private List<UserLevel> getUserLevel(Long merchantId){
return null;
}
public MetaResponse getMetadata(Long merchantId, List<String> modules) {
JSONObject content = new JSONObject();
modules.parallelStream().forEach(module -> content.put(module, metaFunMap.get(meta).apply(merchantId)));
return new MetaResponse(content);
}
}
思路
- 定义一个Map,key:每个数据模块的唯一标识,与前端协商保持一致,value:获取每个模块数据的函数
- 在当前Bean实例化时,初始化Map
- 前端请求时,运用并行流遍历每个模块(key),从Map中取出待执行的函数,执行,并将执行结果存入JSON中,最后响应给前端
后续再分享java8的其它好玩的用法。