本文主要讲 Redis 的使用,如何与 SpringBoot 项目整合,如何使用注解方式和 RedisTemplate 方式实现缓存。最后会给一个用 Redis 实现分布式锁,用在秒杀系统中的案例。html
更多 Redis 的实际运用场景请关注开源项目 coderiver
前端
项目地址:github.com/cachecats/c…java
NoSQL(NoSQL = Not Only SQL ),意即“不只仅是SQL”,泛指非关系型的数据库。git
随着互联网web2.0网站的兴起,传统的关系数据库在应付web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,暴露了不少难以克服的问题,而非关系型的数据库则因为其自己的特色获得了很是迅速的发展。NoSQL数据库的产生就是为了解决大规模数据集合多重数据种类带来的挑战,尤为是大数据应用难题。 -- 百度百科程序员
分类 | 相关产品 | 典型应用 | 数据模型 | 优势 | 缺点 |
---|---|---|---|---|---|
键值(key-value) | Tokyo、 Cabinet/Tyrant、Redis、Voldemort、Berkeley DB | 内容缓存,主要用于处理大量数据的高访问负载 | 一系列键值对 | 快速查询 | 存储的数据缺乏结构化 |
列存储数据库 | Cassandra, HBase, Riak | 分布式的文件系统 | 以列簇式存储,将同一列数据存在一块儿 | 查找速度快,可扩展性强,更容易进行分布式扩展 | 功能相对局限 |
文档数据库 | CouchDB, MongoDB | Web应用(与Key-Value相似,value是结构化的) | 一系列键值对 | 数据结构要求不严格 | 查询性能不高,并且缺少统一的查询语法 |
图形(Graph)数据库 | Neo4J, InfoGrid, Infinite Graph | 社交网络,推荐系统等。专一于构建关系图谱 | 图结构 | 利用图结构相关算法 | 须要对整个图作计算才能得出结果,不容易作分布式集群方案 |
网上有不少 Redis 的安装教程,这里就很少说了,只说下 Docker 的安装方法:github
Docker 安装运行 Redisweb
docker run -d -p 6379:6379 redis:4.0.8
复制代码
若是之后想启动 Redis 服务,打开命令行,输入如下命令便可。redis
redis-server
复制代码
使用前先引入依赖算法
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
复制代码
使用缓存有两个前置步骤spring
在 pom.xml
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
复制代码
在启动类上加注解 @EnableCaching
@SpringBootApplication
@EnableCaching
public class SellApplication {
public static void main(String[] args) {
SpringApplication.run(SellApplication.class, args);
}
}
复制代码
经常使用的注解有如下几个
@Cacheable
属性以下图
用于查询和添加缓存,第一次查询的时候返回该方法返回值,并向 Redis 服务器保存数据。
之后调用该方法先从 Redis 中查是否有数据,若是有直接返回 Redis 缓存的数据,而不执行方法里的代码。若是没有则正常执行方法体中的代码。
value 或 cacheNames 属性作键,key 属性则能够看做为 value 的子键, 一个 value 能够有多个 key 组成不一样值存在 Redis 服务器。
验证了下,value 和 cacheNames 的做用是同样的,都是标识主键。两个属性不能同时定义,只能定义一个,不然会报错。
condition 和 unless 是条件,后面会讲用法。其余的几个属性不经常使用,其实我也不知道怎么用…
@CachePut
更新 Redis 中对应键的值。属性和 @Cacheable
相同
@CacheEvict
删除 Redis 中对应键的值。
在须要加缓存的方法上添加注解 @Cacheable(cacheNames = "product", key = "123")
,
cacheNames
和 key
都必须填,若是不填 key
,默认的 key
是当前的方法名,更新缓存时会由于方法名不一样而更新失败。
如在订单列表上加缓存
@RequestMapping(value = "/list", method = RequestMethod.GET)
@Cacheable(cacheNames = "product", key = "123")
public ResultVO list() {
// 1.查询全部上架商品
List<ProductInfo> productInfoList = productInfoService.findUpAll();
// 2.查询类目(一次性查询)
//用 java8 的特性获取到上架商品的全部类型
List<Integer> categoryTypes = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypes);
List<ProductVO> productVOList = new ArrayList<>();
//数据拼装
for (ProductCategory category : productCategoryList) {
ProductVO productVO = new ProductVO();
//属性拷贝
BeanUtils.copyProperties(category, productVO);
//把类型匹配的商品添加进去
List<ProductInfoVO> productInfoVOList = new ArrayList<>();
for (ProductInfo productInfo : productInfoList) {
if (productInfo.getCategoryType().equals(category.getCategoryType())) {
ProductInfoVO productInfoVO = new ProductInfoVO();
BeanUtils.copyProperties(productInfo, productInfoVO);
productInfoVOList.add(productInfoVO);
}
}
productVO.setProductInfoVOList(productInfoVOList);
productVOList.add(productVO);
}
return ResultVOUtils.success(productVOList);
}
复制代码
可能会报以下错误
对象未序列化。让对象实现 Serializable
方法便可
@Data
public class ProductVO implements Serializable {
private static final long serialVersionUID = 961235512220891746L;
@JsonProperty("name")
private String categoryName;
@JsonProperty("type")
private Integer categoryType;
@JsonProperty("foods")
private List<ProductInfoVO> productInfoVOList ;
}
复制代码
生成惟一的 id 在 IDEA 里有一个插件:GenerateSerialVersionUID
比较方便。
重启项目访问订单列表,在 rdm 里查看 Redis 缓存,有 product::123
说明缓存成功。
在须要更新缓存的方法上加注解: @CachePut(cacheNames = "prodcut", key = "123")
注意
cacheNames
和key
要跟@Cacheable()
里的一致,才会正确更新。
@CachePut()
和@Cacheable()
注解的方法返回值要一致
在须要删除缓存的方法上加注解:@CacheEvict(cacheNames = "prodcut", key = "123")
,执行完这个方法以后会将 Redis 中对应的记录删除。
cacheNames
也能够统一写在类上面, @CacheConfig(cacheNames = "product")
,具体的方法上就不用写啦。
@CacheConfig(cacheNames = "product")
public class BuyerOrderController {
@PostMapping("/cancel")
@CachePut(key = "456")
public ResultVO cancel(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId){
buyerService.cancelOrder(openid, orderId);
return ResultVOUtils.success();
}
}
复制代码
Key 也能够动态设置为方法的参数
@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId){
OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
return ResultVOUtils.success(orderDTO);
}
复制代码
若是参数是个对象,也能够设置对象的某个属性为 key。好比其中一个参数是 user 对象,key 能够写成 key="#user.id"
缓存还能够设置条件。
设置当 openid 的长度大于3时才缓存
@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid", condition = "#openid.length > 3")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId){
OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
return ResultVOUtils.success(orderDTO);
}
复制代码
还能够指定 unless
即条件不成立时缓存。#result
表明返回值,意思是当返回码不等于 0 时不缓存,也就是等于 0 时才缓存。
@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid", condition = "#openid.length > 3", unless = "#result.code != 0")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId){
OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
return ResultVOUtils.success(orderDTO);
}
复制代码
与使用注解方式不一样,注解方式能够零配置,只需引入依赖并在启动类上加上 @EnableCaching
注解就可使用;而使用 RedisTemplate 方式麻烦些,须要作一些配置。
第一步仍是引入依赖和在启动类上加上 @EnableCaching
注解。
而后在 application.yml
文件中配置 Redis
spring:
redis:
port: 6379
database: 0
host: 127.0.0.1
password:
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
timeout: 5000ms
复制代码
而后写个 RedisConfig.java
配置类
package com.solo.coderiver.user.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
复制代码
Redis 的配置就完成了。
Redis 能够存储键与5种不一样数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。
下面来对这5种数据结构类型做简单的介绍:
结构类型 | 结构存储的值 | 结构的读写能力 |
---|---|---|
String | 能够是字符串、整数或者浮点数 | 对整个字符串或者字符串的其中一部分执行操做;对象和浮点数执行自增(increment)或者自减(decrement) |
List | 一个链表,链表上的每一个节点都包含了一个字符串 | 从链表的两端推入或者弹出元素;根据偏移量对链表进行修剪(trim);读取单个或者多个元素;根据值来查找或者移除元素 |
Set | 包含字符串的无序收集器(unorderedcollection),而且被包含的每一个字符串都是独一无二的、各不相同 | 添加、获取、移除单个元素;检查一个元素是否存在于某个集合中;计算交集、并集、差集;从集合里卖弄随机获取元素 |
Hash | 包含键值对的无序散列表 | 添加、获取、移除单个键值对;获取全部键值对 |
Zset | 字符串成员(member)与浮点数分值(score)之间的有序映射,元素的排列顺序由分值的大小决定 | 添加、获取、删除单个元素;根据分值范围(range)或者成员来获取元素 |
RedisTemplate 对五种数据结构分别定义了操做
redisTemplate.opsForValue();
操做字符串
redisTemplate.opsForHash();
操做hash
redisTemplate.opsForList();
操做list
redisTemplate.opsForSet();
操做set
redisTemplate.opsForZSet();
操做有序set
若是操做字符串的话,建议用 StringRedisTemplate
。
StringRedisTemplate 继承了 RedisTemplate。
RedisTemplate 是一个泛型类,而 StringRedisTemplate 则不是。
StringRedisTemplate 只能对 key=String,value=String 的键值对进行操做,RedisTemplate 能够对任何类型的 key-value 键值对操做。
他们各自序列化的方式不一样,但最终都是获得了一个字节数组,异曲同工,StringRedisTemplate 使用的是 StringRedisSerializer 类;RedisTemplate 使用的是 JdkSerializationRedisSerializer 类。反序列化,则是一个获得 String,一个获得 Object
二者的数据是不共通的,StringRedisTemplate 只能管理 StringRedisTemplate 里面的数据,RedisTemplate 只能管理 RedisTemplate中 的数据。
在须要使用 Redis 的地方,用 @Autowired
注入进来
@Autowired
RedisTemplate redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
复制代码
因为项目中暂时仅用到了 StringRedisTemplate 与 RedisTemplate 的 Hash 结构,StringRedisTemplate 比较简单就不贴代码了,下面仅对操做 Hash 进行举例。
关于 RedisTemplate 的详细用法,有一篇文章已经讲的很细很好了,我以为不必再去写了。传送门
package com.solo.coderiver.user.service.impl;
import com.solo.coderiver.user.dataobject.UserLike;
import com.solo.coderiver.user.dto.LikedCountDTO;
import com.solo.coderiver.user.enums.LikedStatusEnum;
import com.solo.coderiver.user.service.LikedService;
import com.solo.coderiver.user.service.RedisService;
import com.solo.coderiver.user.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class RedisServiceImpl implements RedisService {
@Autowired
RedisTemplate redisTemplate;
@Autowired
LikedService likedService;
@Override
public void saveLiked2Redis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.LIKE.getCode());
}
@Override
public void unlikeFromRedis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.UNLIKE.getCode());
}
@Override
public void deleteLikedFromRedis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}
@Override
public void incrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, 1);
}
@Override
public void decrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -1);
}
@Override
public List<UserLike> getLikedDataFromRedis() {
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED, ScanOptions.NONE);
List<UserLike> list = new ArrayList<>();
while (cursor.hasNext()) {
Map.Entry<Object, Object> entry = cursor.next();
String key = (String) entry.getKey();
//分离出 likedUserId,likedPostId
String[] split = key.split("::");
String likedUserId = split[0];
String likedPostId = split[1];
Integer value = (Integer) entry.getValue();
//组装成 UserLike 对象
UserLike userLike = new UserLike(likedUserId, likedPostId, value);
list.add(userLike);
//存到 list 后从 Redis 中删除
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}
return list;
}
@Override
public List<LikedCountDTO> getLikedCountFromRedis() {
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE);
List<LikedCountDTO> list = new ArrayList<>();
while (cursor.hasNext()) {
Map.Entry<Object, Object> map = cursor.next();
//将点赞数量存储在 LikedCountDT
String key = (String) map.getKey();
LikedCountDTO dto = new LikedCountDTO(key, (Integer) map.getValue());
list.add(dto);
//从Redis中删除这条记录
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, key);
}
return list;
}
}
复制代码
讲完了基础操做,再说个实战运用,用Redis 实现分布式锁 。
实现分布式锁以前先看两个 Redis 命令:
SETNX
将key
设置值为value
,若是key
不存在,这种状况下等同SET命令。 当key
存在时,什么也不作。SETNX
是”SET if Not eXists”的简写。
返回值
Integer reply, 特定值:
1
若是key被设置了0
若是key没有被设置例子
redis> SETNX mykey "Hello"
(integer) 1
redis> SETNX mykey "World"
(integer) 0
redis> GET mykey
"Hello"
redis>
复制代码
GETSET
自动将key对应到value而且返回原来key对应的value。若是key存在可是对应的value不是字符串,就返回错误。
设计模式
GETSET能够和INCR一块儿使用实现支持重置的计数功能。举个例子:每当有事件发生的时候,一段程序都会调用INCR给key mycounter加1,可是有时咱们须要获取计数器的值,而且自动将其重置为0。这能够经过GETSET mycounter “0”来实现:
INCR mycounter
GETSET mycounter "0"
GET mycounter
复制代码
返回值
bulk-string-reply: 返回以前的旧值,若是以前Key
不存在将返回nil
。
例子
redis> INCR mycounter
(integer) 1
redis> GETSET mycounter "0"
"1"
redis> GET mycounter
"0"
redis>
复制代码
这两个命令在 java 中对应为 setIfAbsent
和 getAndSet
分布式锁的实现:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
@Slf4j
public class RedisLock {
@Autowired
StringRedisTemplate redisTemplate;
/** * 加锁 * @param key * @param value 当前时间 + 超时时间 * @return */
public boolean lock(String key, String value){
if (redisTemplate.opsForValue().setIfAbsent(key, value)){
return true;
}
//解决死锁,且当多个线程同时来时,只会让一个线程拿到锁
String currentValue = redisTemplate.opsForValue().get(key);
//若是过时
if (!StringUtils.isEmpty(currentValue) &&
Long.parseLong(currentValue) < System.currentTimeMillis()){
//获取上一个锁的时间
String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
if (StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)){
return true;
}
}
return false;
}
/** * 解锁 * @param key * @param value */
public void unlock(String key, String value){
try {
String currentValue = redisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)){
redisTemplate.opsForValue().getOperations().delete(key);
}
}catch (Exception e){
log.error("【redis锁】解锁失败, {}", e);
}
}
}
复制代码
使用:
/** * 模拟秒杀 */
public class SecKillService {
@Autowired
RedisLock redisLock;
//超时时间10s
private static final int TIMEOUT = 10 * 1000;
public void secKill(String productId){
long time = System.currentTimeMillis() + TIMEOUT;
//加锁
if (!redisLock.lock(productId, String.valueOf(time))){
throw new SellException(101, "人太多了,等会儿再试吧~");
}
//具体的秒杀逻辑
//解锁
redisLock.unlock(productId, String.valueOf(time));
}
}
复制代码
更多 Redis 的具体使用场景请关注开源项目 CodeRiver
,致力于打造全平台型全栈精品开源项目。
coderiver 中文名 河码,是一个为程序员和设计师提供项目协做的平台。不管你是前端、后端、移动端开发人员,或是设计师、产品经理,均可以在平台上发布项目,与志同道合的小伙伴一块儿协做完成项目。
coderiver河码 相似程序员客栈,但主要目的是方便各细分领域人才之间技术交流,共同成长,多人协做完成项目。暂不涉及金钱交易。
计划作成包含 pc端(Vue、React)、移动H5(Vue、React)、ReactNative混合开发、Android原生、微信小程序、java后端的全平台型全栈项目,欢迎关注。
您的鼓励是我前行最大的动力,欢迎点赞,欢迎送小星星✨ ~