redis(k-v)高速緩存 + springboot2.x.x
1、nosql
1)特點
- 通常是以key-value形式存儲
- 不支持sql語句
- 沒有表結構
2)優點
- 高併發讀寫性能
- 大數據量擴展(分佈式存儲)
- 配置簡單
- 靈活高效
- 低廉成本
3)缺點
- 沒有統一標準
- 沒有正式官方支持
- 各種產品還不算成熟
4)常見nosql產品
redis、mongoDB
2、redis
- remote dictionary server遠程數據服務
- 一款內存高速緩存數據庫
- 用C編寫
- 數據模型爲key-value
- 支持存儲的value:String\hash\list鏈表\set集合\Zset有序集合
- 爲了保證效率,數據都是緩存在內存中,它也可以週期性的把更新的數據寫入磁盤或者把修改操作寫入追加的記錄文件。
- redis的string可以包含任何類型,包括jpg或序列化對象
特點:
- 高速讀取數據
- 減輕數據庫壓力
- 有集合功能(優於普通數據庫和同類別產品)
- 多張數據結構支持
適用場景:
- 【sort set】排行榜應用、取 top操作、【如新浪微博熱門話題】
- 【list】獲取最新的N個數據 、或者某個分類的最新數據
- 【set】將用戶的好友/粉絲/關注,可以存在一個sorted set中,score可以是timestamp,這樣求兩個人的共同好友的操作,可能就只需要用求交集命令即可
如:sns獲得共同好友 - 【set】防供給系統(ip判斷)等等
- 【Hash】計數:
喜歡數,評論數,鑑定數,瀏覽數,etc【INCR,DECR】
動態數、關注數、粉絲數、喜歡商品數、發帖數 - 用戶Timeline/Feeds
與memcache比較說明:
- memcache支持數據類型就是String
- memcache存儲到內存裏面,一旦斷電或重啓則數據丟失,但redis持久化,週期性把數據保存到硬盤裏面,導致重啓或斷電不會丟失數據
- memcache一個鍵存儲的數據最大時1M,而redis的一個鍵值,存儲的最大數據量是1G
3、使用
1、注入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置文件
spring:
cache:
type: redis
redis:
time-to-live: 20000 #緩存超時時間ms
cache-null-values: false #是否緩存空值
redis:
database: 1
host:
port: 6379
password:
timeout: 10000 #redis 連接超時時間ms
package com.fish.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/* 1.x.x
@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
// 開啓使用緩存名稱最爲key前綴
redisCacheManager.setUsePrefix(true);
//這裏可以設置一個默認的過期時間 單位是秒
redisCacheManager.setDefaultExpiration(redisDefaultExpiration);
// 設置緩存的過期時間
Map<String, Long> expires = new HashMap<>();
expires.put("people", 1000);
redisCacheManager.setExpires(expires);
return redisCacheManager;
}
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1L)).disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
return cacheManager;
}
/**
* retemplate相關配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置連接工廠
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修飾符範圍,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會跑出異常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值採用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 設置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 對hash類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 對redis字符串類型數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 對鏈表類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 對無序集合類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 對有序集合類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
/* 處理redis緩存異常的類
* redis異常後,db能繼續響應客戶端請求,然後記錄這次異常,回頭再處理
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
System.out.println(key);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
System.out.println(value);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
}
};
return cacheErrorHandler;
}
}
3、工具類
package com.fish.utils;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
/**
* 寫入緩存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設置時效時間
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量刪除對應的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量刪除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 刪除對應的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判斷緩存中是否有對應的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 讀取緩存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希獲取數據
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表獲取
*
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合獲取
*
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合獲取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
4、連接到redis
5、對要緩存的類對象model/entity實現序列化
implements Serializable
6、熟悉一些操作
1)
StringRedisTemplate StringRedisTemplate;
RedisTemplate redisTemplate;
這兩者的數據是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate裏面的數據,RedisTemplate只能管理RedisTemplate中的數據
2)
Set set = redisTemplate.keys("*");
獲取所有的key
3)redisTemplate.opsForValue();
操作字符串
redisTemplate.opsForHash();
操作hash
redisTemplate.opsForList();
操作list
4)
redisTemplate如何注入到ValueOperations
5)
operations.set(key, value, 5, TimeUnit.HOURS); //5h redis中的數據失效
存入緩存
operations.get(key);
從緩存中根據key取出想要的
7、設計key
1)設計項目需要在何處使用緩存有效高效減輕服務器的壓力。
2)設計key以存在大量數據時如何在根據你設的key取出想要數據