最近換工作以後,結結實實的寫了幾個月的業務。需求完結以後,就找找自己喜歡的東西寫寫,換個口味。
擼碼最難的就是給變量取名字了。所以就寫一個變量生成器吧。
演示如下:
實現思路:
使用了 Mac 上最出名的效率工具 Alfred
。利用 Alfred
調用本地的 python
腳本,利用 http 模塊,請求遠程的 API 接口。
遠程 API 獲取查詢的字符後,首先使用結巴分詞
,對查詢的句子進行分詞,然後調用有道詞典的 API 翻譯,拼接以後返回。
最終,一個回車就能把結果輸入到我們的 IDE 裏面減少很多操作,媽媽再也不會擔心我取不出變量名啦。
API 的實現:
既然說換個口味,那 API 我肯定不會使用 'Spring mvc' 啦。
主要採用的是 'vertx' 這個基於'netty' 的全異步的 java 庫。有興趣的同學可以參考 http://vartx.io 。
使用 Spring boot 管理對象的生命週期。
使用 “結巴分詞” 對查詢的語句進行分詞。
使用 guava cache 來對查詢結果進行緩存。爲啥要緩存?主要是有道的翻譯API是收費的,查完把結果緩存起來能節約一點算一點。
至於爲什麼使用本地緩存而不是 Redis?因爲阿里雲的 Redis 一個月要25塊錢啊。自己搭一個?我的vps 一共只有 1G 內存啊。
說到底,架構設計需要考慮實際情況,一味上高大上的技術也不可取。適合的纔是最好的。
vertx-web
寫過 netty
的同學就知道,netty
的業務邏輯是寫在一個個的 handler
中的。
同樣 vertx
也類似於 netty
也是使用 handler
來處理請求。
vertx 通過 Router 這個類,將請求路由到不同的 Handler 中。所以我們直接看代碼:
@Component public class StaticServer extends AbstractVerticle { @Autowired private VariableHandler variableHandler; @Override public void start() throws Exception { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.post("/api/hump").handler(routingContext ->variableHandler.get(routingContext)); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } }
我們把 VariableHandler
綁定到了 ’/api/hump‘ 這個 uri 的 post 方法上了。服務器啓動以後會監聽 ’8080‘ 端口。 vertx-web的運行是不需要類似 tomcat 這樣的容器的。
RestTemplate
我們一般是用 Httpclient
在代碼中調用 http 接口。但是我覺得 HTTPClient 封裝的不是很好。我們可以直接使用 Spring boot web
提供的 RestTemplate (真香)。直接看代碼:
private ApiResponse requestYoudao(String param){ long timeMillis = System.currentTimeMillis(); String salt = String.valueOf(timeMillis); String sign = Md5Utils.md5(appKey + param + salt + secretKey); MultiValueMap<String,String> bodyMap = new LinkedMultiValueMap<>(); bodyMap.add("q",param); bodyMap.add("from","auto"); bodyMap.add("to","auto"); bodyMap.add("appKey",appKey); bodyMap.add("salt",salt); bodyMap.add("sign",sign); MultiValueMap<String,String> headersMap = new LinkedMultiValueMap<>(); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headersMap); return restTemplate.postForObject(url, requestEntity,ApiResponse.class); }
Guava
Guava 是 google 提供的一個java 基礎庫類,如果會使用 Guava 的話,會成倍的提升你的開發效率。在本項目中主要使用 Guava 提供的本地緩存和字符串操作:
Guava cache 的使用很簡單直接看代碼:
@Autowired private Cache<String,ApiResponse> cache; private ApiResponse cachedResponse(String param){ try { return cache.get(param, () -> requestYoudao(param)); }catch (Exception e){ log.error("error",e); } return null; }
Guava 對提供了很多給力的字符串的操作。尤其是對字符串下劃線,大小寫,駝峯形式,提供的強有力的支持。這樣使得我們的 API 提供各種風格的變量形式。我們直接看代:
switch (status){ case Constants.LOWER_CAMEL: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,underline); case Constants.LOWER_HYPHEN: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN,underline); case Constants.LOWER_UNDERSCORE: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE,underline); case Constants.UPPER_CAMEL: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL,underline); case Constants.UPPER_UNDERSCORE: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE,underline); default: return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,underline); }
以上就是 API 接口的實現。
python 腳本
本地的python 腳本就極其簡單了:
# -*- coding:utf-8 -*- import httplib,urllib,json url = 'xilidou.com' def query(q,status=0): response = get(q,status) dates = json.loads(response.read()) items = list() for date in dates: item = {} item['title'] = date.encode('utf-8') item['arg'] = date.encode('utf-8') item['subtitle'] = '回車複製' item['icon'] = getIcon() items.append(item) jsonBean = {} jsonBean['items'] = items json_str = json.dumps(jsonBean) if json_str: print json_str return str def get(q,status=0): parameters= dict() parameters['q'] = q parameters['status'] = status parameters = urllib.urlencode(parameters) headers = {"Content-type": "application/x-www-form-urlencoded"} conn = httplib.HTTPSConnection(url) conn.request('POST','/api/hump',parameters,headers) response = conn.getresponse() return response def getIcon(): icon = {} icon['path'] = 'icon.png' return icon if __name__ == '__main__': query('中文')
幹兩件事情:
- 從 Alfred 中獲取用戶輸入的待查詢字符串。
- 調用遠程的 API 接口獲取返回後格式化然後打印結果。
Alfred
大家可以直接下載 github 代碼。在 python 文件夾裏面找到 hump.alfredworkflow
雙擊。就安裝到你的 Mac 上了。
前提是你的 Mac 安裝了 aflred 且付費成爲高級用戶。
最後
github 地址:
https://github.com/diaozxin007/HumpApi
我之前還開發了一個利用 aflred 直接查詢有道詞典的 workflow。效果如下圖:
下載地址如下:
https://www.xilidou.com/2017/10/24/%E6%9C%89%E9%81%93-Alfred-Workflow-%E5%A8%81%E5%8A%9B%E5%8A%A0%E5%BC%BA%E7%89%88/。