自己定制一個Springboot-stater

自己開發(fā)一個spring boot starter的步驟

  • 新建一個項目,
  • 需要一個配置類椿猎,配置類里面需要裝備好需要提供出去的類
  • 1)使用@Enable,使用@Import導入需要裝配的類
    2)/META-INF/spring.factories牺弹,在org.springframework.boot.autoconfigure.EnableAutoConfiguration配置需要裝備的類蟀俊。

自己寫個demo,寫一個springboot-redis-stater項目小泉,整合jedis芦疏。
依賴如下:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>1.5.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

定義一個實體類,為下面在配置文件中配置屬性然后自動配置JedisPoolConfig類到spring容器中:

@ConfigurationProperties(prefix="redis.pool")
public class JedisPoolConfigProperties {

    private int maxTotal; //最大連接數(shù)

    private int maxIdle; //最大空閑連接數(shù)

    private int minIdle; //初始化連接數(shù)

    private long maxWait; //最大等待時間

    private boolean testOnBorrow; //對拿到的connection進行validateObject校驗

    private boolean testOnReturn; //在進行returnObject對返回的connection進行validateObject校驗

    private boolean testWhileIdle; //定時對線程池中空閑的鏈接進行validateObject校驗

    public int getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public long getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(long maxWait) {
        this.maxWait = maxWait;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public boolean isTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }
}

同樣的道理微姊,定義一個實體類酸茴,為下面在配置文件中配置屬性然后將JedisPool納入到spring容器中。

@ConfigurationProperties(prefix="redis")
public class RedisProperties {
    private String host;
    private Integer port;
    private Integer timeout;
    private String password;
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public Integer getPort() {
        return port;
    }
    public void setPort(Integer port) {
        this.port = port;
    }

    public Integer getTimeout() {
        return timeout;
    }

    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

配置相關(guān)的JedisPoolConfig和JedisPool兢交,

@Configuration
@ConditionalOnClass(Jedis.class)
@EnableConfigurationProperties(value = {RedisProperties.class,JedisPoolConfigProperties.class})
public class RedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public JedisPoolConfig jedisPoolConfig(JedisPoolConfigProperties jedisPoolConfigProperties){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(jedisPoolConfigProperties.getMaxTotal());
        jedisPoolConfig.setMaxIdle(jedisPoolConfigProperties.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(jedisPoolConfigProperties.getMaxWait());
        jedisPoolConfig.setTestOnBorrow(jedisPoolConfigProperties.isTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(jedisPoolConfigProperties.isTestOnReturn());
        jedisPoolConfig.setTestWhileIdle(jedisPoolConfigProperties.isTestWhileIdle());
        return jedisPoolConfig;
    }

    @Autowired
    private JedisPoolConfig jedisPoolConfig;

    @Bean
    @ConditionalOnMissingBean
    public JedisPool jedisPool(RedisProperties redisProperties){
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),
                redisProperties.getTimeout(),redisProperties.getPassword());
        return jedisPool;

    }

}

定義redis的工具類接口薪捍,使用Jedis工具類

public interface RedisCacheService {


    //根據(jù)緩存key獲取值
    Object getCache(Serializable cacheKey);


    //設(shè)置緩存數(shù)據(jù)的key-value,并設(shè)置失效時間配喳,單位為秒
    boolean putCache(Serializable cacheKey, Object objValue, int expiration);

    //清除緩存
    void removeCache(Serializable cacheKey);


    //向指定list集合中添加對象,在list尾部添加對象
    boolean putListCache(Serializable cacheKey, Object objValue);


    //向指定list集合中添加對象晴裹,并指定位置坐標
    boolean putListCache(Serializable cacheKey, Object objValue,
                                int index);

    /**
     * 根據(jù)坐標,返回一段集合
     *
     * @param cacheKey
     * @param start
     *            起始坐標 頭部為0
     * @param end
     *            結(jié)束坐標 尾部為-1
     * @return
     */
    public List<Object> getListCache(Serializable cacheKey, int start, int end);


    //返回結(jié)合
    List<Object> getListCache(Serializable cacheKey);

    /**
     * 裁剪list集合
     *
     * @param cacheKey
     * @param start
     *            起始坐標
     * @param end
     *            結(jié)束坐標
     * @return
     */
    boolean trimListCache(Serializable cacheKey, int start, int end);


    //添加map集合
    boolean putMapCache(Serializable cacheKey, Map<Object, Object> map);

    //map中的鍵值
    boolean deleteMapCache(Serializable cacheKey, Serializable mapKey);


    //獲取map中的值
    Object getMapValueCache(Serializable cacheKey, Serializable mapKey);


    //緩存key是否存在
    boolean exists(Serializable cacheKey);


    //設(shè)置key的失效時間
    boolean setKeyExpire(String cacheKey, int expiration);
}

實現(xiàn)

@Service("redisCacheService")
public class RedisCacheServiceImpl implements RedisCacheService {

    private static final Logger logger = LoggerFactory.getLogger(RedisCacheServiceImpl.class);

    private static final String JEDIS_SET_RETURN_OK = "OK";

    @Autowired
    protected JedisPool jedisPool;

    /**
     * 同步獲取Jedis實例
     * @return Jedis
     */
    public synchronized Jedis getJedis() {
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            logger.error("Get jedis from jedisPool,  error : ",e);
        }
        return jedis;
    }

    @Override
    public Object getCache(Serializable cacheKey) {
        Jedis jedis =getJedis();
        Object obj=null;
        try {
            obj= SerializingUtil.deserialize((byte[]) jedis.get(SerializingUtil.serialize(cacheKey)));
        } catch (Exception e) {
            logger.error("getCache,  error cacheKey=: "+cacheKey,e);
        }finally{
            jedis.close();
        }
        return obj;
    }

    @Override
    public boolean putCache(Serializable cacheKey, Object objValue,
                            int expiration) {
        Jedis jedis =getJedis();
        try {
            String result = jedis.setex(SerializingUtil.serialize(cacheKey), expiration, SerializingUtil.serialize(objValue));
            if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) {
                return true;
            }
        } catch (Exception e) {
            logger.error("putCache,  error : cacheKey="+cacheKey+" ,objValue="+objValue+" expiration="+expiration,e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public void removeCache(Serializable cacheKey) {
        Jedis jedis =getJedis();
        try {
            jedis.del(SerializingUtil.serialize(cacheKey));
        } catch (Exception e) {
            logger.error("removeCache,  error cacheKey=: "+cacheKey,e);
        }finally{
            jedis.close();
        }
    }

    @Override
    public boolean putListCache(Serializable cacheKey, Object objValue) {
        Jedis jedis =getJedis();
        try {
            Long num = jedis.rpush(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(objValue));
            if (num > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("putListCache,  error : ",e);
        }finally{
            jedis.close();
        }

        return false;
    }

    @Override
    public boolean putListCache(Serializable cacheKey, Object objValue, int index) {
        Jedis jedis =getJedis();
        try {
            String result = jedis.lset(SerializingUtil.serialize(cacheKey), index, SerializingUtil.serialize(objValue));
            if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) {
                return true;
            }
        } catch (Exception e) {
            logger.error("putListCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public List<Object> getListCache(Serializable cacheKey, int start, int end) {
        Jedis jedis =getJedis();
        try {
            List<byte[]> list = jedis.lrange(SerializingUtil.serialize(cacheKey), start, end);
            if (null != list && list.size() > 0) {
                List<Object> objList = new ArrayList<Object>();
                for (byte[] b : list) {
                    objList.add(SerializingUtil.deserialize(b));
                }
                return objList;
            }
        } catch (Exception e) {
            logger.error("getListCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return null;
    }

    @Override
    public List<Object> getListCache(Serializable cacheKey) {
        return getListCache(cacheKey, 0, -1);
    }

    @Override
    public boolean trimListCache(Serializable cacheKey, int start, int end) {
        Jedis jedis =getJedis();
        try {
            String result = jedis.ltrim(SerializingUtil.serialize(cacheKey), start, end);
            if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) {
                return true;
            }
        } catch (Exception e) {
            logger.error("trimListCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public boolean putMapCache(Serializable cacheKey, Map<Object, Object> map) {
        Jedis jedis =getJedis();
        try {
            if (null != map && !map.isEmpty()) {
                Map<byte[], byte[]> byteMap = new HashMap<>();
                for (Map.Entry<Object, Object> entry: map.entrySet()) {
                    byteMap.put(SerializingUtil.serialize(entry.getKey()), SerializingUtil.serialize(entry.getValue()));
                }
                String result = jedis.hmset(SerializingUtil.serialize(cacheKey), byteMap);
                if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) {
                    return true;
                }
                return true;
            }
        } catch (Exception e) {
            logger.error("putMapCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public boolean deleteMapCache(Serializable cacheKey, Serializable mapKey) {
        Jedis jedis =getJedis();
        try {
            Long result = jedis.hdel(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(mapKey));
            if (result > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("deleteMapCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public Object getMapValueCache(Serializable cacheKey, Serializable mapKey) {
        Jedis jedis =getJedis();
        try {
            List<byte[]> list = jedis.hmget(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(mapKey));
            if (null != list && list.size() > 0) {
                return SerializingUtil.deserialize(list.get(0));
            }
        } catch (Exception e) {
            logger.error("getMapValueCache,  error : ",e);
        }finally{
            jedis.close();
        }
        return null;
    }

    @Override
    public boolean exists(Serializable cacheKey) {
        Jedis jedis =getJedis();
        try {
            return jedis.exists(SerializingUtil.serialize(cacheKey));
        } catch (Exception e) {
            logger.error("exists,  error cacheKey=: "+cacheKey,e);
        }finally{
            jedis.close();
        }
        return false;
    }

    @Override
    public boolean setKeyExpire(String cacheKey, int expiration) {
        Jedis jedis =getJedis();
        try {
            Long result = jedis.expire(SerializingUtil.serialize(cacheKey), expiration);
            if (result > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("setKeyExpire,  error : cacheKey="+cacheKey+" expiration="+expiration,e);
        }finally{
            jedis.close();
        }
        return false;
    }

}

再建一個項目,引入springboot-redis-stater依賴:

    <dependencies>
        <dependency>
            <groupId>com.zhihao.miao</groupId>
            <artifactId>springboot-redis-stater</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

在配置文件配置redis信息:

redis.pool.maxTotal=1024
redis.pool.maxIdle=120
redis.pool.minIdle=10
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true

redis.host=
redis.port=6389
redis.password=
redis.timeout=1000

測試:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        RedisCacheService redisCacheService = context.getBean(RedisCacheService.class);
        boolean flag = redisCacheService.putCache("name","miaozhihao00",3000);
        System.out.println(flag);
        Object object = redisCacheService.getCache("name");
        System.out.println(object);
        context.close();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末钮追,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子阿迈,更是在濱河造成了極大的恐慌元媚,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惠毁,死亡現(xiàn)場離奇詭異,居然都是意外死亡鞠绰,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進店門屿笼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來翁巍,“玉大人驴一,你說我怎么就攤上這事灶壶。” “怎么了驰凛?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵恰响,是天一觀的道長趣钱。 經(jīng)常有香客問我胚宦,道長,這世上最難降的妖魔是什么枢劝? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任您旁,我火速辦了婚禮低矮,結(jié)果婚禮上被冒,老公的妹妹穿的比我還像新娘轮蜕。我一直安慰自己,他們只是感情好跃洛,可當我...
    茶點故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布汇竭。 她就那樣靜靜地躺著葱蝗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪皂甘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天悼凑,我揣著相機與錄音偿枕,去河邊找鬼。 笑死户辫,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的渔欢。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼苫幢,長吁一口氣:“原來是場噩夢啊……” “哼披坏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起棒拂,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤帚屉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后攻旦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡且预,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年烙无,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片截酷。...
    茶點故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖三热,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情就漾,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布催跪,位于F島的核電站夷野,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏悯搔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一通危、第九天 我趴在偏房一處隱蔽的房頂上張望灌曙。 院中可真熱鬧菊碟,春花似錦在刺、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽纯陨。三九已至留储,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間获讳,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留尤误,地道東北人侠畔。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓软棺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親喘落。 傳聞我的和親對象是個殘疾皇子最冰,可洞房花燭夜當晚...
    茶點故事閱讀 43,658評論 2 350

推薦閱讀更多精彩內(nèi)容