自己開發(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();
}
}