typeahead + JDK 8 并行流 + redis 高速即时查询.

时间:2023-03-09 09:47:07
typeahead + JDK 8 并行流 + redis  高速即时查询.

感谢JDK8,让我们JAVA 程序员暂时不用担心失业.

有些情况,需要根据用户输入值,即时查询数据库,MYSQL显然不再适合这种业务.

mongoDB看似最适合,但是为了这么一个破功能,也不值得特意去搞一个

根据现有的redis,配合JDK8并行数据流,效果还不错

 <input autocomplete="off" data-provide="typeahead" class="form-control input-sm" name="itemCode" id="itemCode" placeholder="物品编码">
   function fillLocalData(typeaheadObj) {
        $(typeaheadObj).typeahead({
            source: function (query, process) {
                if (isBlank(query) && query.length < 3)
                    return;
                $.get("/searchByKeyWord/" + query, function (data) {
                    if (data.operateCode == "S") {
                        process(data.datas);
                    }
                });
            },
//            items: 8,//最多显示个数
            updater: function (item) {
                return item.split(":")[0];//这里一定要return,否则选中不显示,外加调用display的时候null reference错误。
            },
            displayText: function (item) {
                return item;//返回字符串
            },
            afterSelect: function (item) {
                //选择项之后的事件 ,item是当前选中的。
            },
            delay: 0//延迟时间
        });
    }

数据在程序启动的时候已经缓存到redis键是ITEM_MAP

    public Map<String,String> getCacheMap() {
        BoundHashOperations<String, String, String> hashOperations = redisTemplate.boundHashOps(ITEM_MAP);
        return hashOperations.entries();
    }

并行数据流在一定程度上弥补了redis查询的弱势

public String [] searchByKeyWord(String keyWord){
        Map<String,String> cacheMap = this.getCacheMap();
    return cacheMap.entrySet().stream().parallel().filter(entry->entry.getValue().indexOf(keyWord)!=-1).map(val->val.getKey()+":"+val.getValue()).limit(5).toArray(String [] ::new);
}