package com.shopping.app.util;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Service;import redis.clients.jedis.*;import java.util.List;import java.util.Map;import java.util.Set;import redis.clients.jedis.BinaryClient.LIST_POSITION;import redis.clients.util.SafeEncoder;@Servicepublic class RedisManager { @Autowired @Qualifier("jedisPool") JedisPool jedisPool; private Logger log = Logger.getLogger(this.getClass()); /** 操作Key的方法 */ public Keys KEYS = new Keys(); /** 对存储结构为String类型的操作 */ public Strings STRINGS = new Strings(); /** 对存储结构为List类型的操作 */ public Lists LISTS = new Lists(); /** 对存储结构为Set类型的操作 */ public Sets SETS =new Sets(); /** 对存储结构为HashMap类型的操作 */ public Hash HASH = new Hash(); /** 对存储结构为Set(排序的)类型的操作 */ public SortSet SORTSET = new SortSet();public Long orderId(String prefix){ Jedis jedis = jedisPool.getResource(); String key = "tl_order_id" + prefix; String orderId = null; try { Long index = jedis.incr(key); //00001 orderId = prefix + String.format("%1$05d", index); }catch(Exception e){ System.out.println("生成订单号异常"); }finally { if(null != jedis){ jedis.close(); } } return Long.valueOf(orderId); }}
package com.shopping.test;import com.shopping.app.util.RedisManager;import org.springframework.beans.factory.annotation.Autowired;import redis.clients.jedis.Jedis;import java.util.Calendar;import java.util.Date;public class Test { @Autowired RedisManager redisManager; public static String getOrderIDPrefix(Date date){ Calendar c = Calendar.getInstance(); c.setTime(date); int year = c.get(Calendar.YEAR); int day = c.get(Calendar.DAY_OF_YEAR); //从今天属于今年的第多少天?365 2位 3位 267 001 int hour = c.get(Calendar.HOUR_OF_DAY); String dayFmt = String.format("%1$03d", day); String hourFmt = String.format("%1$02d", hour); return (year - 2000) + dayFmt + hourFmt; }
}
String prefix= Test.getOrderIDPrefix(new Date()); System.out.println(prefix); String orderId=redisManager.orderId(prefix).toString(); System.out.println("生成的订单号:"+orderId);