Java8 函数式编程项目实战

173

Java8 函数式编程实战

业务场景

前端传递当前商户下一个或多个配置的key,从服务器获取每个key对应的数据。

请求:

var url = http://localhost:8080/api/merchant/1/metadata?modules=shop,paymentType,user,userLevel

响应:

{
	"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){
        // 从数据库中查询Shop数据
        return null;
    }

    private List<PaymentType> getPaymentType(Long merchantId){
        // 从数据库中查询PaymentType数据
        return null;
    }

    private List<User> getUser(Long merchantId){
        // 从数据库中查询User数据
        return null;
    }

    private List<UserLevel> getUserLevel(Long merchantId){
        // 从数据库中查询UserLevel数据
        return null;
    }

    /**
     * 动态获取商户元数据-并行操作
     */
    public MetaResponse getMetadata(Long merchantId, List<String> modules) {
        // 将每个key查询的结果存入JSON
        JSONObject content = new JSONObject();
        // 并行查询每个key的数据
        modules.parallelStream().forEach(module -> content.put(module, metaFunMap.get(meta).apply(merchantId)));
        // 响应结果
        return new MetaResponse(content);
    }
}

思路

  1. 定义一个Map,key:每个数据模块的唯一标识,与前端协商保持一致,value:获取每个模块数据的函数
  2. 在当前Bean实例化时,初始化Map
  3. 前端请求时,运用并行流遍历每个模块(key),从Map中取出待执行的函数,执行,并将执行结果存入JSON中,最后响应给前端

后续再分享java8的其它好玩的用法。