自己定制一个Springboot-stater

自己开发一个spring boot starter的步骤

  • 新建一个项目,
  • 需要一个配置类,配置类里面需要装备好需要提供出去的类
  • 1)使用@Enable,使用@Import导入需要装配的类
    2)/META-INF/spring.factories,在org.springframework.boot.autoconfigure.EnableAutoConfiguration配置需要装备的类。

自己写个demo,写一个springboot-redis-stater项目,整合jedis。
依赖如下:

    
        
            org.springframework.boot
            spring-boot-starter
            1.5.4.RELEASE
        
        
            redis.clients
            jedis
        
        
            commons-lang
            commons-lang
            2.6
        
    

定义一个实体类,为下面在配置文件中配置属性然后自动配置JedisPoolConfig类到spring容器中:

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

    private int maxTotal; //最大连接数

    private int maxIdle; //最大空闲连接数

    private int minIdle; //初始化连接数

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

配置相关的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 {


    //根据缓存key获取值
    Object getCache(Serializable cacheKey);


    //设置缓存数据的key-value,并设置失效时间,单位为秒
    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);

    /**
     * 根据坐标,返回一段集合
     *
     * @param cacheKey
     * @param start
     *            起始坐标 头部为0
     * @param end
     *            结束坐标 尾部为-1
     * @return
     */
    public List getListCache(Serializable cacheKey, int start, int end);


    //返回结合
    List getListCache(Serializable cacheKey);

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


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

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


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


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


    //设置key的失效时间
    boolean setKeyExpire(String cacheKey, int expiration);
}
 
 

实现

@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 getListCache(Serializable cacheKey, int start, int end) {
        Jedis jedis =getJedis();
        try {
            List list = jedis.lrange(SerializingUtil.serialize(cacheKey), start, end);
            if (null != list && list.size() > 0) {
                List objList = new ArrayList();
                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 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 map) {
        Jedis jedis =getJedis();
        try {
            if (null != map && !map.isEmpty()) {
                Map byteMap = new HashMap<>();
                for (Map.Entry 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 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依赖:

    
        
            com.zhihao.miao
            springboot-redis-stater
            1.0-SNAPSHOT
        
        
            org.springframework.boot
            spring-boot-starter
        
    

在配置文件配置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();
    }
}
自己定制一个Springboot-stater_第1张图片

你可能感兴趣的:(自己定制一个Springboot-stater)