一、redis介紹
redis
是一種NoSQL類型的數據庫,其數據存儲在內存中,因此其數據查詢效率很高,很快。常被用作數據緩存
,分布式鎖
等。SpringBoot集成了Redis,可查看開發文檔Redis開發文檔。Redis有自己的可視化工具Redis Desktop Manager
。
Redis使用RedisTemplate
和StringRedisTemplate
類提供的方法操作redis數據。
redis使用場景:
1、即時性、數據一致性要求不高的
2、訪問量大且更新頻率不高的數據(讀多,寫少)
二、redis使用方法
- 導包
<!-- redis依賴包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies>
說明:具體依賴包名可在Maven倉庫搜索redis即可查詢到
- 寫配置
spring:redis:host: 192.168.195.131(redis地址)
說明:redis可配置項可以ctrl+點擊redis查看所有RedisProperties
- 使用
RedisTemplate
和StringRedisTemplate
類提供的方法操作redis數據。
@Overridepublic Map<String, List<Level2CategoryVO>> getCatalogJson() {// 先從緩存中查,如果有則直接返回,如果沒有則查數據庫,再返回String catalogJson = redisTemplate.opsForValue().get("catalogJson");// 如果緩存中沒有,則查數據庫,將結果存到redis,再返回if (StringUtil.isNullOrEmpty(catalogJson)) {Map<String, List<Level2CategoryVO>> catalogJsonDB = this.getCatalogJsonDB();redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonDB));return catalogJsonDB;}return JSON.parseObject(catalogJson, new HashMap<String, List<Level2CategoryVO>>().getClass());}
redis可視化結果:
說明:
StringRedisTemplate
類是專門在redis中操作key和value均為String類型的數據。RedisTemplate
則value可為對象類型。