spring boot 注意坑

1、spring boot從官網生成後須要增長如下pom才能啓動:java

<!--web應用基本環境配置 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

2、spring 與redis集成:web

1.pom中增長:redis

<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.9.0</version>
</dependency>

2.增長配置類RedisConfigspring

package com.zdnst.platform.system.config;

import com.zdnst.platform.system.config.dubbo.DubboProperties;
import com.zdnst.platform.system.face.RedisFace;
import com.zdnst.platform.system.impl.RedisFaceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.repository.cdi.RedisKeyValueTemplateBean;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {

    @Autowired
    RedisProperties redisProperties;

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisConnectionFactory getConnectionFactory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisProperties.getHost());
        factory.setPort(redisProperties.getPort());
        factory.setPassword(redisProperties.getPassword());
        factory.setUsePool(true);
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        return factory;
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }


//
//    @Bean
//    public RedisTemplate<?, ?> getRedisTemplate(){
//        RedisTemplate<?,?> template = new RedisKeyValueTemplateBean(getConnectionFactory());
//        return template;
//    }

}

三、編寫redisFace緩存

/**
 * Copyright(C) 2012-2014 GuangZhou zdnst Co., Ltd. All Rights Reserved.<br/>
 * 版權全部(C)2012-2014 <br/>
 * 公司名稱:廣州支點科技有限公司<br/>
 * 公司地址:廣州市天河區天源路401號之三E2棟<br/>
 * 網址:http://www.100100system.com/<br/>
 * <p>標        題:</p>
 * <p>文  件  名:com.zdnst.maps.core.services.impl.RedisServiceImpl.java</p>
 * <p>部        門:研發一部
 * <p>版        本: 1.0</p>
 * <p>Compiler: JDK1.6.0_21</p>
 * <p>創  建  者:yongqin.zhong</p>
 * <p>建立時間:May 21, 20154:11:41 PM</p>
 * <p>修  改  者:</p>
 * <p>修改時間:</p>
 */
package com.zdnst.platform.system.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zdnst.common.constant.BaseCode;
import com.zdnst.common.util.Constants;
import com.zdnst.common.util.DateUtils;
import com.zdnst.common.util.StringUtils;
import com.zdnst.common.util.ThreadPoolUtils;
import com.zdnst.platform.system.exception.PlatformSystemException;
import com.zdnst.platform.system.face.RedisFace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;


@Service("redisFace")
public class RedisFaceImpl implements RedisFace {
   
   /**
    * 日誌打印,使用org.slf4j.Logger
    */
   protected Logger logger = LoggerFactory.getLogger(getClass());


   private ExecutorService pool = ThreadPoolUtils.getPool();

   /**
    * redis spring template added by pengzh 2015-4-15
    */
   @Autowired
   protected RedisTemplate<Serializable, Serializable> redisTemplate;

   @Override
   public void setMinTimeValue(final Serializable key, final Serializable value,
         final Integer mins) throws PlatformSystemException {

      pool.submit(new Runnable(){
         @Override
         public void run() {
            try {

               redisTemplate.opsForValue().set(key, value);
               if(mins!=null&&mins>0){
                  redisTemplate.expire(key,mins,TimeUnit.MINUTES);
               }
            }catch (PlatformSystemException e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //必須拋出通知調用者
               throw new PlatformSystemException(e.getCode(),e.getMessage());
            } catch (Exception e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
               throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
            }
         }

      });
   }
   


   @Override
   public void setHourTimeValue(final Serializable key, final Serializable value,
         final Integer hours) throws PlatformSystemException{
      pool.submit(new Runnable(){
         @Override
         public void run() {
            try {
               redisTemplate.opsForValue().set(key, value);
               if(hours!=null&&hours>0){
                  redisTemplate.expire(key,hours,TimeUnit.HOURS);
               }
            }catch (PlatformSystemException e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //必須拋出通知調用者
               throw new PlatformSystemException(e.getCode(),e.getMessage());
            } catch (Exception e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
               throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
            }
         }

      });
   }

   @Override
   public void setDaysTimeValue(final Serializable key, final Serializable value,
         final Integer days) throws PlatformSystemException{
      pool.submit(new Runnable(){
         @Override
         public void run() {
            try {
               redisTemplate.opsForValue().set(key, value);
               if(days!=null&&days>0){
                  redisTemplate.expire(key,days,TimeUnit.DAYS);
               }
            } catch (Exception e) {
               e.printStackTrace();
            }
         }

      });

   }

   @Override
   public void expire(final  Serializable key, final  Integer days, TimeUnit timeUnit) throws PlatformSystemException {
      if(days!=null&&days>0){
         redisTemplate.expire(key,days,timeUnit);
      }
   }

   @Override
   public Serializable get(Object key) throws PlatformSystemException{
      try {
         if(StringUtils.isNotEmpty((String) key)){
            return redisTemplate.opsForValue().get(key);
         }
         else{
            return null;
         }
      }catch (PlatformSystemException e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //必須拋出通知調用者
         throw new PlatformSystemException(e.getCode(),e.getMessage());
      } catch (Exception e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
         throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
      }
   }

   @Override
   public void remove(final Object KeyLike)throws PlatformSystemException{
      pool.submit(new Runnable(){
         @Override
         public void run() {
            try {
               Set<Serializable> setKeys= redisTemplate.keys(KeyLike+"*");
               if(setKeys!=null&&setKeys.size()>0){
                  Iterator<Serializable> it = setKeys.iterator();
                  while (it.hasNext()) {
                     Serializable oneKey = it.next();
                     redisTemplate.delete(oneKey);
                  }
               }
            }catch (PlatformSystemException e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //必須拋出通知調用者
               throw new PlatformSystemException(e.getCode(),e.getMessage());
            } catch (Exception e) {
               //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
               logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
               //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
               throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
            }
         }

      });

   }

   @Override
   public void delete(final Serializable key)throws PlatformSystemException {
      try {
         if(StringUtils.isNotEmpty((String) key)){
            redisTemplate.delete(key);
         }
      }catch (PlatformSystemException e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //必須拋出通知調用者
         throw new PlatformSystemException(e.getCode(),e.getMessage());
      } catch (Exception e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
         throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
      }
   }

   /**
    * 獲取流水號
    * @param seqKey
    * @return
    * @throws PlatformSystemException
    */
   @Override
   public String getSeq(String seqKey) throws PlatformSystemException {
      try {
         Integer seq = (Integer) this.get(seqKey);
         if(seq == null) {
            seq = 1;
         }else{
            //從新插入序列號
            if(seq == 9999){
               seq = 1;
            }else{
               seq ++;
            }
         }
         this.setMinTimeValue(seqKey, seq, null);
         String fSeq=this.gengercode(4, seq+"",DateUtils.DATE_FORMAT_YYYYMMDD);
         return fSeq;
      }catch (PlatformSystemException e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //必須拋出通知調用者
         throw new PlatformSystemException(e.getCode(),e.getMessage());
      } catch (Exception e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
         throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
      }
   }
   /**
    * 獲取流水號
    * @param maxLen 流水號長度
    * @param code 流水號
    * @return
    */
   public String gengercode(int maxLen,String code,String format){
      String genCode = code;
      int len = maxLen - code.length();
      for(int i=0;i<len;i++){
         genCode ="0"+genCode;
      }
      String currDate  = DateUtils.formatDate(new Date(), format);
      return currDate+genCode;
   }

   /**
    * 獲取導出文件名流水號:年月日+兩位遞增編號;緩存時間爲一天
    * @param seqKey
    * @return
    * @throws PlatformSystemException
    */
   @Override
   public String getSeq(String seqKey,int maxLenth) throws PlatformSystemException {
      try {
         Integer seq = (Integer) this.get(seqKey);
         if(seq == null) {
            seq = 1;
         }else{
            //從新插入序列號
            if(seq == 99){
               seq = 1;
            }else{
               seq ++;
            }
         }
         this.setHourTimeValue(seqKey, seq, 1);
         String fSeq=this.gengercode(2, seq+"", DateUtils.DATE_FORMAT_YYYYMMDD);
         return fSeq;
      }catch (PlatformSystemException e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //必須拋出通知調用者
         throw new PlatformSystemException(e.getCode(),e.getMessage());
      } catch (Exception e) {
         //打印服務層異常詳情,注意第二個參數必須傳打印異常堆棧
         logger.error(Constants.EX_SERVICE_EXCEPTION + BaseCode.getMsg(e), e);
         //封裝爲服務層異常110網絡超時後再拋出,必須拋出通知調用者
         throw new PlatformSystemException(BaseCode.ERROR_CODE602.code,e.getMessage());
      }
   }
}

3、tomcat

相關文章
相關標籤/搜索