redis 生成訂單號學習
阿新 • • 發佈:2018-12-11
題目是生成明天的訂單號,刪除昨天的訂單號,在redis操作,訂單號暫定規則為年月日接五位數。如2018102200001
當一個訂單生成的時候, 去redis去取訂單號,去玩後刪掉。這個取和刪除操作是一個命令發過去的。不能寫成兩個語句。
參考部落格:
redis五種結構詳解:
https://www.cnblogs.com/sdgf/p/6244937.html
redis五種結構詳解:
https://blog.csdn.net/kiss199203/article/details/73549091
redis設定list的過期時間
http://lionlx.iteye.com/blog/1746683
redis儲存list
https://blog.csdn.net/Kincym/article/details/72676813
最終程式碼:
/** * 明天的訂單號 * @return */ @ResponseBody @RequestMapping(value="/ordergen",produces = "application/json;charset=UTF-8") public String ordergen(){ JSONObject jsonObject = new JSONObject(); try{ //用於儲存的訂單列表 //List<String> ordernumlist = new ArrayList<String>(); //準備前部分訂單號碼 Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, +1);//明天 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String str_q = sdf.format(calendar.getTime()); //準備後部分訂單號碼 for(int i=1;i<=9;i++){ String str_h = String.valueOf(i); String strmax ="00000"; str_h=strmax.substring(0, 5-str_h.length())+str_h; String str_qh = str_q + str_h; //redis儲存一個list,從頭開始,往後加 redisClient.rpush(str_q,str_qh); } //明天的訂單號,將從今天開始存在48小時(今天只能取到今天的key,時間一到list自動沒了) redisClient.expire(str_q, 172800); jsonObject.put("code", ResponseStatusCode.SUCC.getValue()); return jsonObject.toJSONString(); }catch(Exception e){ e.printStackTrace(); jsonObject.put("code", ResponseStatusCode.FAIL.getValue()); return jsonObject.toJSONString(); } } /** * 獲取並且刪除訂單號 * @return */ @ResponseBody @RequestMapping(value="/ordertake",produces = "application/json;charset=UTF-8") public String ordertake(){ JSONObject jsonObject = new JSONObject(); try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String str_q = sdf.format(new Date()); String ordernow = redisClient.lpop(str_q); jsonObject.put("code", ResponseStatusCode.SUCC.getValue()); jsonObject.put("ordernum", ordernow); return jsonObject.toJSONString(); }catch(Exception e){ e.printStackTrace(); jsonObject.put("code", ResponseStatusCode.FAIL.getValue()); return jsonObject.toJSONString(); } }
創作思路: