一蔫磨、緩存概述
緩存是分布式系統(tǒng)中的重要組件淘讥,主要解決高并發(fā)圃伶,大數(shù)據(jù)場景下堤如,熱點數(shù)據(jù)訪問的性能問題。提供高性能的數(shù)據(jù)快速訪問窒朋。
1搀罢、緩存的原理
將數(shù)據(jù)寫入/讀取速度更快的存儲(設(shè)備);
將數(shù)據(jù)緩存到離應(yīng)用最近的位置侥猩;
將數(shù)據(jù)緩存到離用戶最近的位置榔至。
2、緩存分類
在分布式系統(tǒng)中欺劳,緩存的應(yīng)用非常廣泛唧取,從部署角度有以下幾個方面的緩存應(yīng)用。
CDN緩存划提;
反向代理緩存枫弟;
分布式Cache;
本地應(yīng)用緩存鹏往;
3淡诗、緩存媒介
常用中間件:Varnish,Ngnix,Squid韩容,Memcache款违,Redis,Ehcache等群凶;
緩存的內(nèi)容:文件插爹,數(shù)據(jù),對象请梢;
緩存的介質(zhì):CPU递惋,內(nèi)存(本地,分布式)溢陪,磁盤(本地萍虽,分布式)
4、緩存設(shè)計
緩存設(shè)計需要解決以下幾個問題:
緩存什么形真?
哪些數(shù)據(jù)需要緩存:1.熱點數(shù)據(jù)杉编;2.靜態(tài)資源。
緩存的位置咆霜?
CDN邓馒,反向代理,分布式緩存服務(wù)器蛾坯,本機(jī)(內(nèi)存光酣,硬盤)
如何緩存的問題?
過期策略
固定時間:比如指定緩存的時間是30分鐘脉课;
相對時間:比如最近10分鐘內(nèi)沒有訪問的數(shù)據(jù)救军;
同步機(jī)制
實時寫入;(推)
異步刷新倘零;(推拉)
二唱遭、Redis
1、搭建
以docker的形式搭建
docker?run?-di?--name=mytest_redis?-p?6379:6379?redis
2呈驶、SpringDataRedis
Spring-data-redis是spring大家族的一部分拷泽,提供了在srping應(yīng)用中通過簡單的配置訪問
redis服務(wù),對reids底層開發(fā)包(Jedis,?JRedis,?and?RJC)進(jìn)行了高度封裝袖瞻,RedisTemplate
提供了redis各種操作司致。
1)在pom.xml中引依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2)修改application.yml,在spring節(jié)點下添加配置
redis:
??host:?192.168.184.134
3)在類中引入RedisTemplate
@Autowired
private?RedisTemplate?redisTemplate;
/**
*?根據(jù)ID查詢實體
*?@param?id
*?@return
*/
public?Hello?findById(String?id)?{
//從緩存中提取
Hello?hello=
(Hello)redisTemplate.opsForValue().get("hello_"+id);
//?如果緩存沒有則到數(shù)據(jù)庫查詢并放入緩存
if(hello==null)?{
hello?=?helloDao.findById(id).get();
redisTemplate.opsForValue().set("hello_"?+?id,?hello);
}
return?Hello;
}
/**
*?修改
*?@param?hello
*/
public?void?update(Hello?hello)?{
redisTemplate.delete(?"hello_"?+?hello.getId()?);//刪除緩存
helloDao.save(hello);
}?/
**
*?刪除
*?@param?id
*/
public?void?deleteById(String?id)?{
redisTemplate.delete(?"hello_"?+?id?);//刪除緩存
helloDao.deleteById(id);
}
//緩存過期處理,如設(shè)置1天的過期時間
redisTemplate.opsForValue().set("hello_"?+?id,?hello,1,
TimeUnit.DAYS);
參考
官網(wǎng)http://redisinaction.com/preview/chapter1.html
https://blog.csdn.net/qq_26517369/article/details/78330694