Spring-boot整合Redis
阿新 • • 發佈:2021-11-02
pom檔案
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.5.6</version>
</dependency>
配置類
Redisconfig
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @Author LiGuangLong * @Date 2021-11-01 9:58 * @Version 1.0 **/ @Configuration public class RedisConfig { @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); //設定工廠連結 redisTemplate.setConnectionFactory(redisConnectionFactory); //設定自定義序列化方式要不然redisgui中顯示16進位制 setSerializeConfig(redisTemplate, redisConnectionFactory); return redisTemplate; } private void setSerializeConfig(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) { //對字串採取普通的序列化方式 適用於key 因為我們一般採取簡單字串作為key StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //普通的string型別的key採用 普通序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); //普通hash型別的key也使用 普通序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); //解決查詢快取轉換異常的問題 大家不能理解就直接用就可以了 這是springboot自帶的jackson序列化類,但是會有一定問題 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //普通的值採用jackson方式自動序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //hash型別的值也採用jackson方式序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); //屬性設定完成afterPropertiesSet就會被呼叫,可以對設定不成功的做一些預設處理 redisTemplate.afterPropertiesSet(); } }
備註: 可以避免序列化物件
如果不進行自定義序列化存放的key和value都是預設序列化(16進位制資料) java中進行取得時候會預設反序列化
如果進行了自定義序列化 取值得時候進行判斷會出錯
所以現在存入資料的時候轉為String 取得時候在吧 String 轉為json物件
net.sf.json JSONArray.fromObject(list).toString() //list轉字串 list<e> 可以是物件 JSONArray.fromObject(redis.get("sfzxx")) // 獲取 給物件沒什麼區別就是 swagger 沒有提示了 jsonObject.toString() //存 JSONObject.fromObject(redis.get("dpdtsj")); // 取
雖然不太好但是也可以用
使用阿里巴巴的json庫可以解決swagger問題
JSON.toJSONString(list) //list<dto> list<dto>轉字串存入
List<TollStation> list =JSON.parseArray(redis.get("sfzxx"),TollStation.class); //取 並提供list中物件的型別
String s = JSON.toJSONString(user);//dto轉字串
User user1 = JSON.parseObject(s, User.class);
String b="["+s+"]";
List<User> users = JSON.parseArray(b, User.class); //字串轉 list<dto>
工具類
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
/**
* @Author LiGuangLong
* @Date 2021-11-01 10:18
* @Version 1.0
**/
@Component
@Slf4j
public class RedisUtils {
@Resource
private RedisTemplate<String,Object> redisTemplate;
public Object get(String key){
return key == null ? null : redisTemplate.opsForValue().get(key);
}
//本來只可以放入string型別,但是我們配置了自動序列化所以這兒可以傳入object
public boolean set(String key,Object value){
try{
redisTemplate.opsForValue().set(key,value);
return true;
}catch (Exception e){
log.error("redis set value exception:"+ e);
return false;
}
}
public boolean setex(String key,Object value,long expire){
try{//TimeUnit.SECONDS指定型別為秒
redisTemplate.opsForValue().set(key,value,expire, TimeUnit.SECONDS);
return true;
}catch (Exception e){
log.error("redis set value and expire exception:"+e);
return false;
}
}
public boolean expire(String key,long expire){
try{//這兒沒有ops什麼的是因為每種資料型別都能設定過期時間
redisTemplate.expire(key,expire,TimeUnit.SECONDS);
return true;
}catch (Exception e){
log.error("redis set key expire exception:"+e);
return false;
}
}
public long ttl(String key){
return redisTemplate.getExpire(key);
}
public void del(String ...keys){
if(keys!=null&&keys.length>0) {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(keys));
}
}
public long incrBy(String key,long step){
return redisTemplate.opsForValue().increment(key,step);
}
public boolean setnx(String key,Object value){
return redisTemplate.opsForValue().setIfAbsent(key,value);
}
public boolean setnxAndExpire(String key,Object value,long expire){
return redisTemplate.opsForValue().setIfAbsent(key,value,expire,TimeUnit.SECONDS);
}
public Object getAndSet(String key,Object value){
return redisTemplate.opsForValue().getAndSet(key,value);
}
}
對於介面請求慢的可以 放入redis 並設定超時時間
取得時候判斷下
redis.get("key")==null