如何在项目中使用redis的步骤和遇到的坑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36520235/article/details/81911674

(一)使用redis前的准备

1.需要先自定义一个redis的工具类

1. 定义好redis基本信息


    private static String ADDR_ARRAY = "XXXXX";  

    //private static String ADDR_ARRAY = "localhost";  

    //Redis的端口号  
    private static int PORT = 6379;  

    //访问密码  
//    private static String AUTH = "";

    //可用连接实例的最大数目,默认值为8;  
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。  
    private static int MAX_ACTIVE = 100;

    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。  
    private static int MAX_IDLE = 50;

    //最小空闲连接数, 默认0
    private static int MIN_IDLE=50;

    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;  
    private static int MAX_WAIT = -1;  

    //超时时间  
    private static int TIMEOUT = 10000;

    //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
    private static boolean BLOCK_WHEN_EXHAUSTED = false;

    //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
    private static String EVICTION_POLICY_CLASSNAME="org.apache.commons.pool2.impl.DefaultEvictionPolicy";

    //是否启用pool的jmx管理功能, 默认true
    private static boolean JMX_ENABLED=true;

    private static String JMX_NAME_PREFIX="pool";

    //是否启用后进先出, 默认true
    private static boolean LIFO=true;

    //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
    private static long MIN_EVICTABLE_IDLE_TIME_MILLIS=1800000L;

    //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
    private static long SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS=1800000L;

    //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
    private static int NUM_TESTS_PER_EVICYION_RUN=5;

    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;  
    private static boolean TEST_ON_BORROW = false;

    //在空闲时检查有效性, 默认false
    private static boolean TEST_WHILEIDLE=false;

    //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
    private static long TIME_BERWEEN_EVICTION_RUNS_MILLIS=-1;

    //连接池管理
    private static JedisPool jedisPool = null; 

2. 需要初始化redis的连接池

  /** 
     * 初始化Redis连接池 
     */  
    static {  
        try {  
            JedisPoolConfig config = new JedisPoolConfig();
            config.setBlockWhenExhausted(BLOCK_WHEN_EXHAUSTED);
            config.setEvictionPolicyClassName(EVICTION_POLICY_CLASSNAME); 
            config.setJmxEnabled(JMX_ENABLED);
            config.setJmxNamePrefix(JMX_NAME_PREFIX);
            config.setLifo(LIFO);
            config.setMinEvictableIdleTimeMillis(MIN_EVICTABLE_IDLE_TIME_MILLIS);
            config.setMinIdle(MIN_IDLE);
            config.setNumTestsPerEvictionRun(NUM_TESTS_PER_EVICYION_RUN);
            config.setSoftMinEvictableIdleTimeMillis(SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
            config.setTestOnBorrow(TEST_ON_BORROW);
            config.setTestWhileIdle(TEST_WHILEIDLE);
            config.setTimeBetweenEvictionRunsMillis(TIME_BERWEEN_EVICTION_RUNS_MILLIS);
            config.setMaxTotal(MAX_ACTIVE);  
            config.setMaxIdle(MAX_IDLE);  
            config.setMaxWaitMillis(MAX_WAIT);    
            jedisPool = new JedisPool(config, ADDR_ARRAY, PORT, TIMEOUT);  

            System.out.println("connect to redis ok ");
        } catch (Exception e) {  
//            logger.error("First create JedisPool error : " + e);
            System.out.println("Initialize JedisPool error : " + e);
            e.printStackTrace();
        }  
    }  

3. 设置redis过期时间,以秒为单位

    public final static int EXRP_HOUR = 60 * 60;            //一小时  
    public final static int EXRP_DAY = 60 * 60 * 24;        //一天  
    public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月  

4.销毁释放连接池得到连接池

    /** 
     * 销毁连接池
     * @return void 
     */ 
    public static void end()
    {
        if(null != jedisPool){

            jedisPool.destroy();

            System.out.println("连接池关闭");
        }
    }

    /** 
     * 同步获取Jedis实例 
     * @return Jedis 
     */  
    public static Jedis getJedis() {
        Jedis jedis = null;  
        try {    
            if (jedisPool != null) {    
                jedis = jedisPool.getResource();   
            }  
        } catch (Exception e) {    
//            logger.error("Get jedis error : "+e);  
            System.out.println("getJedis error : "+e);
            e.printStackTrace();
        }

        return jedis;  
    }    

    /** 
     * 释放jedis资源 
     * 
     * @param jedis 
     */  
    public static void returnResource(final Jedis jedis) {  
        if (jedis != null && jedisPool != null) {  
            jedis.close();
//            System.out.println("返回jedis资源!");
        }  
    }  

5.在你需要用到的redis的几种类型中去定义你需要的redis类型

    /** 
     * 设置 List 
     * 
     * @param key 
     * @param value 
     */  
    public static void setListItem(String key, String value) {

        Jedis resource = null;

        try {

            value = StringUtils.isEmpty(value) ? "" : value; 

            resource = getJedis();

            resource.lpush(key, value);

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("setListItem error : " + e); 
            e.printStackTrace(); 

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

    /** 
     * 删除 List中的元素 
     * 
     * @param key 
     * @param value 
     */  
    public static void RemListItem(String key, String value) {

        Jedis resource = null;

        try {

            value = StringUtils.isEmpty(value) ? "" : value; 

            resource = getJedis();

            resource.lrem(key, 1, value);

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("RemListItem error : " + e);
            e.printStackTrace(); 

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

    /** 
     * 获取List值 
     * 
     * @param key 
     * @return value 
     */  
    public static List<String> getListItems(String key) {  

        Jedis resource = null;

        List<String> value = null; 

        try {

            resource = getJedis();

            //如果列表存在,则取出所有
            if (resource.exists(key))
            {
                long len = resource.llen(key);

                value = resource.lrange(key, 0, len-1);     
            }

        } catch (Exception e) {

//          logger.error("Get string error : " + e);
            System.out.println("getListItems error : " + e);
            e.printStackTrace();

        } finally {

            if ( resource != null )
            {
                returnResource(resource);
            }
        }

        return value;  
    }  

    /** 
     * 设置 单条Hash表值
     * 
     * @param key 
     * @param value 
     */  
    public static void setHashItem(String key, Pair<String, String> value) {

        Jedis resource = null;

        try {

            //String pair_val = value.getValue();

            //value.setValue(StringUtils.isEmpty(pair_val) ? "" : pair_val); 

            resource = getJedis();

            resource.hset(key, value.getKey(), value.getValue());

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("setHashItem error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

    /** 
     * 检查Key是否存在
     * @param key 
     * @return value 
     */  
    public static Boolean ExsitKey(String key) {  

        Jedis resource = null;

        Boolean value = false; 

        try {

            resource = getJedis();

            if (resource.exists(key) )
            {   
                value = true;           
            }

        } catch (Exception e) {

//          logger.error("Get string error : " + e);
            System.out.println("ExsitKey error : " + e);
            e.printStackTrace();

        } finally {

            if ( resource != null )
            {
                returnResource(resource);
            }
        }

        return value;  
    }  

    /** 
     * 设置Key的有效期
     * 
     * @param key       要设置的key
     * @param timestamp 设置的有效期限(unix时间戳)
     */  
    public static void setKeyExpireTime(String key, long timestamp) {

        Jedis resource = null;

        try {

            resource = getJedis();

            resource.expireAt(key, timestamp);

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("setKeyExpireTime error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

    /** 
     * 删除Key
     * 
     * @param key       要删除的key
     */  
    public static void removeKey(String key) {

        Jedis resource = null;

        try {

            resource = getJedis();

            resource.del(key);            

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("removeKey error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  
    /** 
     * 检查Hash表中对应的field是否存在
     * 
     * @param key 
     * @return value 
     */  
    public static Boolean ExsitHashItem(String key, String field_name) {  

        Jedis resource = null;

        Boolean value = false; 

        try {

            resource = getJedis();

            if (resource.hexists(key, field_name))
            {   
                value = true;           
            }

        } catch (Exception e) {

//          logger.error("Get string error : " + e);
            System.out.println("ExsitHashItem error : " + e);
            e.printStackTrace();

        } finally {

            if ( resource != null )
            {
                returnResource(resource);
            }
        }

        return value;  
    }  

    /** 
     * 获取指定field的值 
     * 
     * @param key 
     * @return value 
     */  
    public static String getHashItem(String key, String field_name) {  

        Jedis resource = null;

        String value = null; 

        try {

            resource = getJedis();

            value = resource.hget(key, field_name);

        } catch (Exception e) {

//          logger.error("Get string error : " + e);
            System.out.println("getHashItem error : " + e);
            e.printStackTrace();

        } finally {

            if ( resource != null )
            {
                returnResource(resource);
            }
        }

        return value;  
    }  

    /** 
     * 设置 多条Hash表值
     * 
     * @param key 
     * @param value 
     */  
    public static void setHashItems(String key, Map<String, String> value) {

        Jedis resource = null;

        try {

            resource = getJedis();

            resource.hmset(key, value);

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("setHashItems error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  


    /** 
     * 获取所有field的值 
     * 
     * @param key 
     * @return value 
     */  
    public static Map<String, String> getHashItems(String key) {  

        Jedis resource = null;

        Map<String, String> value = null; 

        try {

            resource = getJedis();

            value = resource.hgetAll(key);

        } catch (Exception e) {

//          logger.error("Get string error : " + e);
            System.out.println("getHashItems error : " + e);
            e.printStackTrace();

        } finally {

            if ( resource != null )
            {
                returnResource(resource);
            }
        }

        return value;  
    }  

6.如果需要用到事务的话,也需要自定义事务方法

    /** 
     * 设置布控信息的事务;
     * 
     * @param key 
     * @param value 
     */  
    public static void setEvents(String Listkey, String HashKey, Map<String,String> HashValue, long timestamp) {

        Jedis resource = null;

        try {
            resource = getJedis();

            Transaction transaction = resource.multi();

            transaction.hmset(HashKey, HashValue);

            transaction.expireAt(HashKey, timestamp);

            transaction.lpush(Listkey, HashKey);

            transaction.exec();

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("setEvents error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

    /** 
     * 删除布控信息的事务;
     * 
     * @param key 
     * @param value 
     */  
    public static void removeEvents(String Listkey, String HashKey) {

        Jedis resource = null;

        try {
            resource = getJedis();

            Transaction transaction = resource.multi();

            transaction.del(HashKey);

            transaction.lrem(Listkey, 1, HashKey);

            transaction.exec();

        } catch (Exception e) { 

//            logger.error("Set key error : " + e); 
            System.out.println("removeEvents error : " + e); 
            e.printStackTrace();

        } finally{

            if ( resource != null )
            {
                returnResource(resource);
            }
        }
    }  

(二)自定义真正属于业务的类和其中的方法

1. 为你想要的方法设置一个key,这里需要用到final 和 static

    //首次入城判定时间区间(30天) 
    private final static int FirstEntryTimeSection = 30; 

    //车辆过车记录Hash表名称
    private final static String vehiclePassRecords = "vehiclePassRecords";

    //车辆过车记录Hash表名称
    private final static String vehicleFirstEntryRecords = "vehicleFirstEntryRecords";

    //维稳布控列表名称
    private final static String StabilityItems = "StabilityItems";

    //精准车牌布控列表名称
    private final static String ExactPlateItems = "ExactPlateItems";

    //模糊车牌布控列表名称
    private final static String BlurPlateItems = "BlurPlateItems";

    //车型布控列表名称
    private final static String VehicleTypeItems = "VehicleTypeItems";

    //车辆类别布控列表名称
    private final static String VehicleKindItems = "VehicleKindItems";

2. 这里真正的去写干活的方法,根据具体的业务

        //4. 判断比较车辆类别布控信息
            listVehicleKindItems = JedisUtil.getListItems(VehicleKindItems);

            if ( listVehicleKindItems != null )
            {
                for ( String item : listVehicleKindItems )
                {   
                    if ( JedisUtil.ExsitKey(item) )
                    {
                        Map<String, String> VehicleKindItem = JedisUtil.getHashItems(item);

                        //取得精准号牌布控信息中的布控卡口列表信息,然后比较当前卡口是否在该列表中
                        String bayonetIDList = VehicleKindItem.get("bayonetID");
                        if ( bayonetIDList != null && bayonetIDList.indexOf(bayonetID) >= 0)
                        {
                            //取得布控信息中的布控起始日期,然后判断本次过车时间是否是在布控起始日期之后
                            String BeginDate = VehicleKindItem.get("startdate");                        
                            if ( BeginDate != null && daysOfTwoDates(BeginDate, captureTime.substring(0, 10)) >= 0 )
                            {
                                 String BeginTime = VehicleKindItem.get("starttime");
                                 String EndTime = VehicleKindItem.get("endtime");

                                 //如取得布控信息中的布控起始和终止时间,判断过车时间是不是在该时间区间内,若是,则继续判断车牌号码信息
                                 if ( BeginTime != null && EndTime != null && isInTimeSection(captureTime, BeginTime, EndTime))
                                 {                               
                                     String vbstr = VehicleKindItem.get("vBrand");                               
                                     String vtypestr = VehicleKindItem.get("vType");
                                    //布控信息存在错误时,则跳过此条布控信息
                                     if ( vbstr == null || vtypestr == null )
                                     {
                                         continue;
                                     }

                                     int vbint = Integer.parseInt(vbstr);                                    
                                     int vtypeint = Integer.parseInt(vtypestr);

                                     //如果布控条件中未设定品牌或类型,或设定的品牌类型与本次过车记录中的数据不相同,则中止,然后继续匹配下一条布控信息
                                     if ( (vbint != 0 && vbint != vBrand) || (vtypeint != 0 && vtypeint != vType))
                                     {
                                         continue;
                                     }

                                     String vlpinfo = VehicleKindItem.get("platenumber");

                                     //如果设定了模糊车牌信息,则判断本次过车数据中的车牌信息是否匹配布控信息中的模糊车牌
                                     if ( vlpinfo != null && vlpinfo.length() > 0 )
                                     {
                                         String vlpregx = vlpinfo.replaceAll("\\*", "\\.\\*");

                                         if ( ! vehicleID.matches(vlpregx) )
                                         {
                                             continue;
                                         }
                                     }
                                     //将此条过车警报信息对应的布控信息保存到返回结果之中。
                                     retval.put(item, "4");
                                 }
                            }
                        }
                    }   
                }
            }
        } catch ( Exception e ){

            System.out.println("GetAlarmInfoByOthers error : " + e);

            e.printStackTrace();
        }

        long endTime=System.currentTimeMillis();

        System.out.println("GetAlarmInfoByOthers执行时间:"+(endTime-startTime)+"ms");

        return retval;
    }

     /** 
     * 取得布控信息
     * @param   trapID  布控编号
     * @return  Map<String, String> key:布控数据项名称  value:布控数据项值
     */
    public static Map<String, String> GetTrapInfo(String trapID)
    {   
        Map<String, String> retval = new HashMap<String, String>();

        try {

            if ( JedisUtil.ExsitKey(trapID))
            {
                retval = JedisUtil.getHashItems(trapID);
            }

        } catch (Exception e) {

            System.out.println("GetTrapInfo error : " + e);

            e.printStackTrace();
        }

        return retval;
    }

    /** 
     * 添加布控信息
     * @param   trapID      布控编号
     * @param   trapKind    布控方式
     * @param   trapInfo    布控详细信息
     * @return  boolean true:添加成功  false:添加失败
     */
    public static boolean AddTrapInfo(String trapID, String trapKind, Map<String,String> trapInfo)
    {   
        boolean retval = false;
        long startTime=System.currentTimeMillis();

        try {
            //计算出本次布控到期的时间戳信息
            String dateinfo = trapInfo.get("enddate");
            String timeinfo = trapInfo.get("endtime");
            String datetime = dateinfo + " " + timeinfo;
            long timestamp = Date2TimeStamp(datetime);

            String ListKey = null;

            //精准号牌布控的场合,将布控编码追加到精准号牌布控信息列表中
            if ( "0".equals(trapKind))
            {
                ListKey = ExactPlateItems;

            }
            //模糊号牌布控的场合,将布控编码追加到模糊号牌布控信息列表中
            else if ( "1".equals(trapKind))
            {
                ListKey = BlurPlateItems;

            }
            //维稳布控的场合,将布控编码追加到维稳布控信息列表中
            else if ( "2".equals(trapKind))
            {
                ListKey = StabilityItems;

            }
            //车型布控的场合,将布控编码追加到车型布控信息列表中
            else if ( "3".equals(trapKind))
            {
                ListKey = VehicleTypeItems;

            }
            //车辆类别布控的场合,将布控编码追加到车辆类别布控信息列表中
            else if ( "4".equals(trapKind))
            {
                ListKey = VehicleKindItems;
            }

            //执行事务处理(1,设定布控详细信息的Hash表;2,设定Hash表的有效期;3,将Hash表的Key追加到对应的List列表中;
            JedisUtil.setEvents(ListKey, trapID, trapInfo, timestamp);

            retval = true;

        } catch (Exception e) {

            System.out.println("AddTrapInfo error : " + e);

            e.printStackTrace();
        }

        long endTime=System.currentTimeMillis();

        System.out.println("AddTrapInfo执行时间:"+(endTime-startTime)+"ms");
        return retval;
    }

    /** 
     * 删除布控信息
     * @param   trapID  布控编号
     * @param   trapKind    布控方式
     * @return  boolean true:删除成功  false:删除失败
     */
    public static boolean RemoveTrapInfo(String trapID, String trapKind)
    {   
        boolean retval = false;

        try {       
            String ListKey = null;

            //精准号牌布控的场合,将布控编码从精准号牌布控信息列表中删除
            if ( "0".equals(trapKind))
            {
                ListKey = ExactPlateItems;

            }
            //模糊号牌布控的场合,将布控编码从模糊号牌布控信息列表中删除
            else if ( "1".equals(trapKind))
            {
                ListKey = BlurPlateItems;

            }
            //维稳布控的场合,将布控编码从维稳布控信息列表中删除
            else if ( "2".equals(trapKind))
            {
                ListKey = StabilityItems;

            }
            //车型布控的场合,将布控编码从车型布控信息列表中删除
            else if ( "3".equals(trapKind))
            {
                ListKey = VehicleTypeItems;

            }
            //车辆类别布控的场合,将布控编码从车辆类别布控信息列表中删除
            else if ( "4".equals(trapKind))
            {
                ListKey = VehicleKindItems;
            }

            JedisUtil.removeEvents(ListKey, trapID);

        } catch (Exception e) {

            System.out.println("RemoveTrapInfo error : " + e);

            e.printStackTrace();
        }

        return retval;
    }

总结:调用这些工具类的时候会遇到的坑

1. 首先当你在自己业务中去调用(2)中定义的类时,你不需要用@Autowired去注入,因为你是用的是static来修饰的业务方法,直接用(2)中的类名直接去调用就行了不用注入,不然会报错!!!切记哦

猜你喜欢

转载自blog.csdn.net/qq_36520235/article/details/81911674