在springboot中封裝一個自己的redis模板
阿新 • • 發佈:2018-12-12
新建一個springboot專案
引入依賴
注意引入的不是 spring-boot-starter-data-redis這個依賴
這裡有一個坑,必須引入spring-boot-configuration-processor這個依賴,不然配置檔案裡面的值不能讀取出來
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.38</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
配置檔案
#redis 這個是我們自定義的屬性
redis.host=192.168.220.128
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3
新建一個配置檔案類讀取類
來讀取我們在application.properties中自定義的屬性
package com.example.miaosha_xdp.redis; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Getter @Setter @Component /** * 這個註解讓我們可以讀取到配置檔案中所有以redis開頭到屬性值 */ @ConfigurationProperties(prefix = "redis") public class RedisConfig { private String host; private int port; private int timeout;//秒 private String password; private int poolMaxTotal; private int poolMaxIdle; private int poolMaxWait;//秒 }
新建RedisPoolFactory類
這個用來載入配置檔案類並得到一個redis到連線池
package com.example.miaosha_xdp.service; import com.example.miaosha_xdp.redis.RedisConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @Component public class RedisPoolFactory { @Autowired RedisConfig redisConfig; /** * @Bean這個註解將JedisPool注入到Spring容器中 */ @Bean public JedisPool JedisPoolFactory() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle()); jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal()); jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000); return new JedisPool(jedisPoolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout() * 1000, redisConfig.getPassword(), 0); //上面引數中的0是redis總共有16個庫,我們從0庫開始 } }
使用模板工廠來生成key的字首
我們有一個需要,要求不同的類存入reids必須加上一個響應的字首,下面來實現 :
模板介面
/**
* 模板介面
*/
public interface KeyPrefix {
/**
* 設定超時時間
* @return
*/
int expireSeconds();
/**
* 獲取key的字首
* @return
*/
String getPrefix();
}
模板抽象類
package com.example.miaosha_xdp.redis;
/**
* 定義為抽象類,為了不讓直接使用,而是作為模板讓別的類繼承
*/
public abstract class BasePrefix implements KeyPrefix {
private int expireSeconds;
private String prefix;
public BasePrefix(String prefix) {
//0表示永久有效
this(0,prefix);
}
public BasePrefix(int expireSeconds, String prefix) {
this.expireSeconds = expireSeconds;
this.prefix = prefix;
}
@Override
public int expireSeconds() {
return expireSeconds;
}
@Override
public String getPrefix() {
String className = prefix.getClass().getSimpleName();
return className+":"+prefix;
}
}
實現抽象類具體的子類
package com.example.miaosha_xdp.redis;
public class UserKey extends BasePrefix {
public UserKey(String prefix) {
super(prefix);
}
public static UserKey getId=new UserKey("id");
public static UserKey getName=new UserKey("name");
}
package com.example.miaosha_xdp.redis;
public class OrderKey extends BasePrefix {
public OrderKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
}
}
package com.example.miaosha_xdp.redis;
public class MiaoshaUserKey extends BasePrefix {
public static final int TOKEN_EXPIRE = 3600 * 24 * 2;
public MiaoshaUserKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
};
public static MiaoshaUserKey token=new MiaoshaUserKey(TOKEN_EXPIRE,"token");
}
編寫我們的封裝類
package com.example.miaosha_xdp.redis;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Service
public class RedisService {
@Autowired
private JedisPool jedisPool;
/**
* 獲取單個key值
* @param keyPrefix
* @param key
* @param clazz
* @param <T>
* @return
*/
public <T> T get(KeyPrefix keyPrefix,String key,Class<T> clazz){
Jedis jedis=null;
try {
Jedis poolResource = jedisPool.getResource();
String realKey = keyPrefix.getPrefix() + key;
String stringValue = poolResource.get(realKey);
T t=stringToBean(stringValue,clazz);
return t;
}finally {
returnToPool(jedis);
}
}
/**
* 存入物件
* @param keyPrefix
* @param key
* @param value
* @param <T>
* @return
*/
public <T> boolean set(KeyPrefix keyPrefix,String key,T value){
Jedis jedis=null;
try {
Jedis poolResource = jedisPool.getResource();
String str=beanToString(value);
if (StringUtils.isEmpty(str)){
return false;
}
String realKey = keyPrefix.getPrefix() + key;
int seconds = keyPrefix.expireSeconds();
if(seconds <= 0) {
jedis.set(realKey, str);
}else {
jedis.setex(realKey, seconds, str);
}
return true;
}finally {
returnToPool(jedis);
}
}
/**
* 判斷key是否存在
* */
public <T> boolean exists(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
}finally {
returnToPool(jedis);
}
}
/**
* 增加值
* */
public <T> Long incr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
}
/**
* 減少值
* */
public <T> Long decr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
}
private <T> String beanToString(T value) {
if(value == null) {
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
}
private <T> T stringToBean(String stringValue, Class<T> clazz) {
if (StringUtils.isEmpty(stringValue)||clazz==null){
return null;
}
if (clazz==int.class||clazz==Integer.class){
return (T) Integer.valueOf(stringValue);
}
if (clazz==String.class){
return (T) stringValue;
}
if (clazz==long.class||clazz==Long.class){
return (T) Long.valueOf(stringValue);
}
return JSON.toJavaObject(JSON.parseObject(stringValue),clazz);
}
private void returnToPool(Jedis jedis) {
if (jedis!=null){
jedis.close();
}
}
}