自己定制一個(gè)Springboot-stater

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

  • 新建一個(gè)項(xiàng)目,
  • 需要一個(gè)配置類,配置類里面需要裝備好需要提供出去的類
  • 1)使用@Enable,使用@Import導(dǎo)入需要裝配的類
    2)/META-INF/spring.factories,在org.springframework.boot.autoconfigure.EnableAutoConfiguration配置需要裝備的類。

自己寫個(gè)demo,寫一個(gè)springboot-redis-stater項(xiàng)目,整合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>

定義一個(gè)實(shí)體類,為下面在配置文件中配置屬性然后自動(dòng)配置JedisPoolConfig類到spring容器中:

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

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

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

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

    private long maxWait; //最大等待時(shí)間

    private boolean testOnBorrow; //對(duì)拿到的connection進(jìn)行validateObject校驗(yàn)

    private boolean testOnReturn; //在進(jìn)行returnObject對(duì)返回的connection進(jìn)行validateObject校驗(yàn)

    private boolean testWhileIdle; //定時(shí)對(duì)線程池中空閑的鏈接進(jìn)行validateObject校驗(yàn)

    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;
    }
}

同樣的道理,定義一個(gè)實(shí)體類,為下面在配置文件中配置屬性然后將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è)置失效時(shí)間,單位為秒
    boolean putCache(Serializable cacheKey, Object objValue, int expiration);

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


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


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

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


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

    /**
     * 裁剪list集合
     *
     * @param cacheKey
     * @param start
     *            起始坐標(biāo)
     * @param end
     *            結(jié)束坐標(biāo)
     * @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的失效時(shí)間
    boolean setKeyExpire(String cacheKey, int expiration);
}

實(shí)現(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實(shí)例
     * @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;
    }

}

再建一個(gè)項(xiàng)目,引入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

測(cè)試:

@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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容