Redis详解 - SpringBoot整合Redis,RedisTemplate和注解两种方式的使用

本文主要讲 Redis 的使用,如何与 SpringBoot 项目整合,如何使用注解方式和 RedisTemplate 方式实现缓存。最后会给一个用 Redis 实现分布式锁,用在秒杀系统中的案例。

更多 Redis 的实际运用场景请关注开源项目 coderiver

项目地址:https://github.com/cachecats/coderiver

一、NoSQL 概述

什么是 NoSQL ?

NoSQL(NoSQL = Not Only SQL ),意即“不仅仅是SQL”,泛指非关系型的数据库。

为什么需要 NoSQL ?

随着互联网web2.0网站的兴起,传统的关系数据库在应付web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,暴露了很多难以克服的问题,而非关系型的数据库则由于其本身的特点得到了非常迅速的发展。NoSQL数据库的产生就是为了解决大规模数据集合多重数据种类带来的挑战,尤其是大数据应用难题。 – 百度百科

NoSQL 数据库的四大分类

  • 键值(key-value)存储
  • 列存储
  • 文档数据库
  • 图形数据库
分类相关产品典型应用数据模型优点缺点
键值(key-value)Tokyo、 Cabinet/Tyrant、Redis、Voldemort、Berkeley DB内容缓存,主要用于处理大量数据的高访问负载一系列键值对快速查询存储的数据缺少结构化
列存储数据库Cassandra, HBase, Riak分布式的文件系统以列簇式存储,将同一列数据存在一起查找速度快,可扩展性强,更容易进行分布式扩展功能相对局限
文档数据库CouchDB, MongoDBWeb应用(与Key-Value类似,value是结构化的)一系列键值对数据结构要求不严格查询性能不高,而且缺乏统一的查询语法
图形(Graph)数据库Neo4J, InfoGrid, Infinite Graph社交网络,推荐系统等。专注于构建关系图谱图结构利用图结构相关算法需要对整个图做计算才能得出结果,不容易做分布式集群方案

NoSQL 的特点

  • 易扩展
  • 灵活的数据模型
  • 大数据量,高性能
  • 高可用

二、Redis 概述

Redis的应用场景

  • 缓存
  • 任务队列
  • 网站访问统计
  • 应用排行榜
  • 数据过期处理
  • 分布式集群架构中的 session 分离

Redis 安装

网上有很多 Redis 的安装教程,这里就不多说了,只说下 Docker 的安装方法:

Docker 安装运行 Redis

docker run -d -p 6379:6379 redis:4.0.8

   
  • 1

如果以后想启动 Redis 服务,打开命令行,输入以下命令即可。

redis-server

   
  • 1

使用前先引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

   
  • 1
  • 2
  • 3
  • 4

三、注解方式使用 Redis 缓存

使用缓存有两个前置步骤

  1. pom.xml 引入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
         
    • 1
    • 2
    • 3
    • 4
  2. 在启动类上加注解 @EnableCaching

    @SpringBootApplication
    @EnableCaching
    public class SellApplication {
    	public static void main(String[] args) {
    		SpringApplication.run(SellApplication.class, args);
    	}
    }
    
         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

常用的注解有以下几个

  • @Cacheable

    属性如下图

用于查询和添加缓存,第一次查询的时候返回该方法返回值,并向 Redis 服务器保存数据。

以后调用该方法先从 Redis 中查是否有数据,如果有直接返回 Redis 缓存的数据,而不执行方法里的代码。如果没有则正常执行方法体中的代码。

value 或 cacheNames 属性做键,key 属性则可以看作为 value 的子键, 一个 value 可以有多个 key 组成不同值存在 Redis 服务器。

验证了下,value 和 cacheNames 的作用是一样的,都是标识主键。两个属性不能同时定义,只能定义一个,否则会报错。

condition 和 unless 是条件,后面会讲用法。其他的几个属性不常用,其实我也不知道怎么用…

  • @CachePut

    更新 Redis 中对应键的值。属性和 @Cacheable 相同

  • @CacheEvict

    删除 Redis 中对应键的值。

3.1 添加缓存

在需要加缓存的方法上添加注解 @Cacheable(cacheNames = "product", key = "123"),

cacheNameskey 都必须填,如果不填 key ,默认的 key 是当前的方法名,更新缓存时会因为方法名不同而更新失败。

如在订单列表上加缓存

	@RequestMapping(value = "/list", method = RequestMethod.GET)
    @Cacheable(cacheNames = "product", key = "123")
    public ResultVO list() {
    <span class="token comment">// 1.查询所有上架商品</span>
    List<span class="token generics function"><span class="token punctuation">&lt;</span>ProductInfo<span class="token punctuation">&gt;</span></span> productInfoList <span class="token operator">=</span> productInfoService<span class="token punctuation">.</span><span class="token function">findUpAll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 2.查询类目(一次性查询)</span>
    <span class="token comment">//用 java8 的特性获取到上架商品的所有类型</span>
    List<span class="token generics function"><span class="token punctuation">&lt;</span>Integer<span class="token punctuation">&gt;</span></span> categoryTypes <span class="token operator">=</span> productInfoList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>e <span class="token operator">-</span><span class="token operator">&gt;</span> e<span class="token punctuation">.</span><span class="token function">getCategoryType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    List<span class="token generics function"><span class="token punctuation">&lt;</span>ProductCategory<span class="token punctuation">&gt;</span></span> productCategoryList <span class="token operator">=</span> categoryService<span class="token punctuation">.</span><span class="token function">findByCategoryTypeIn</span><span class="token punctuation">(</span>categoryTypes<span class="token punctuation">)</span><span class="token punctuation">;</span>

    List<span class="token generics function"><span class="token punctuation">&lt;</span>ProductVO<span class="token punctuation">&gt;</span></span> productVOList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//数据拼装</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>ProductCategory category <span class="token operator">:</span> productCategoryList<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
        ProductVO productVO <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ProductVO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//属性拷贝</span>
        BeanUtils<span class="token punctuation">.</span><span class="token function">copyProperties</span><span class="token punctuation">(</span>category<span class="token punctuation">,</span> productVO<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//把类型匹配的商品添加进去</span>
        List<span class="token generics function"><span class="token punctuation">&lt;</span>ProductInfoVO<span class="token punctuation">&gt;</span></span> productInfoVOList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>ProductInfo productInfo <span class="token operator">:</span> productInfoList<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>productInfo<span class="token punctuation">.</span><span class="token function">getCategoryType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>category<span class="token punctuation">.</span><span class="token function">getCategoryType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
                ProductInfoVO productInfoVO <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ProductInfoVO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                BeanUtils<span class="token punctuation">.</span><span class="token function">copyProperties</span><span class="token punctuation">(</span>productInfo<span class="token punctuation">,</span> productInfoVO<span class="token punctuation">)</span><span class="token punctuation">;</span>
                productInfoVOList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>productInfoVO<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
        productVO<span class="token punctuation">.</span><span class="token function">setProductInfoVOList</span><span class="token punctuation">(</span>productInfoVOList<span class="token punctuation">)</span><span class="token punctuation">;</span>
        productVOList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>productVO<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> ResultVOUtils<span class="token punctuation">.</span><span class="token function">success</span><span class="token punctuation">(</span>productVOList<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

可能会报如下错误

对象未序列化。让对象实现 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&lt;ProductInfoVO&gt; productInfoVOList ;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

生成唯一的 id 在 IDEA 里有一个插件:GenerateSerialVersionUID 比较方便。

重启项目访问订单列表,在 rdm 里查看 Redis 缓存,有 product::123 说明缓存成功。

3.2 更新缓存

在需要更新缓存的方法上加注解: @CachePut(cacheNames = "prodcut", key = "123")

注意

  1. cacheNameskey 要跟 @Cacheable() 里的一致,才会正确更新。

  2. @CachePut()@Cacheable() 注解的方法返回值要一致

3.3 删除缓存

在需要删除缓存的方法上加注解:@CacheEvict(cacheNames = "prodcut", key = "123"),执行完这个方法之后会将 Redis 中对应的记录删除。

3.4 其他常用功能

  1. 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();
        }
    }
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  2. 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);
    }
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    如果参数是个对象,也可以设置对象的某个属性为 key。比如其中一个参数是 user 对象,key 可以写成 key="#user.id"

  3. 缓存还可以设置条件。

    设置当 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);
    }
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    还可以指定 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);
    }
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

四、RedisTemplate 使用 Redis 缓存

与使用注解方式不同,注解方式可以零配置,只需引入依赖并在启动类上加上 @EnableCaching 注解就可以使用;而使用 RedisTemplate 方式麻烦些,需要做一些配置。

4.1 Redis 配置

第一步还是引入依赖和在启动类上加上 @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

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

然后写个 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 {

<span class="token annotation punctuation">@Bean</span>
<span class="token annotation punctuation">@ConditionalOnMissingBean</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"redisTemplate"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> RedisTemplate<span class="token generics function"><span class="token punctuation">&lt;</span>String<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span> <span class="token function">redisTemplate</span><span class="token punctuation">(</span>
        RedisConnectionFactory redisConnectionFactory<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> UnknownHostException <span class="token punctuation">{<!-- --></span>

    Jackson2JsonRedisSerializer<span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">&gt;</span></span> jackson2JsonRedisSerializer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Jackson2JsonRedisSerializer</span><span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>Object<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    ObjectMapper om <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ObjectMapper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    om<span class="token punctuation">.</span><span class="token function">setVisibility</span><span class="token punctuation">(</span>PropertyAccessor<span class="token punctuation">.</span>ALL<span class="token punctuation">,</span> JsonAutoDetect<span class="token punctuation">.</span>Visibility<span class="token punctuation">.</span>ANY<span class="token punctuation">)</span><span class="token punctuation">;</span>
    om<span class="token punctuation">.</span><span class="token function">enableDefaultTyping</span><span class="token punctuation">(</span>ObjectMapper<span class="token punctuation">.</span>DefaultTyping<span class="token punctuation">.</span>NON_FINAL<span class="token punctuation">)</span><span class="token punctuation">;</span>
    jackson2JsonRedisSerializer<span class="token punctuation">.</span><span class="token function">setObjectMapper</span><span class="token punctuation">(</span>om<span class="token punctuation">)</span><span class="token punctuation">;</span>

    RedisTemplate<span class="token generics function"><span class="token punctuation">&lt;</span>String<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span> template <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RedisTemplate</span><span class="token generics function"><span class="token punctuation">&lt;</span>String<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>redisConnectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setKeySerializer</span><span class="token punctuation">(</span>jackson2JsonRedisSerializer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setValueSerializer</span><span class="token punctuation">(</span>jackson2JsonRedisSerializer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setHashKeySerializer</span><span class="token punctuation">(</span>jackson2JsonRedisSerializer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setHashValueSerializer</span><span class="token punctuation">(</span>jackson2JsonRedisSerializer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">afterPropertiesSet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> template<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Bean</span>
<span class="token annotation punctuation">@ConditionalOnMissingBean</span><span class="token punctuation">(</span>StringRedisTemplate<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> StringRedisTemplate <span class="token function">stringRedisTemplate</span><span class="token punctuation">(</span>
        RedisConnectionFactory redisConnectionFactory<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> UnknownHostException <span class="token punctuation">{<!-- --></span>
    StringRedisTemplate template <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringRedisTemplate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    template<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>redisConnectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> template<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

Redis 的配置就完成了。

4.2 Redis 的数据结构类型

Redis 可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。

下面来对这5种数据结构类型作简单的介绍:

结构类型结构存储的值结构的读写能力
String可以是字符串、整数或者浮点数对整个字符串或者字符串的其中一部分执行操作;对象和浮点数执行自增(increment)或者自减(decrement)
List一个链表,链表上的每个节点都包含了一个字符串从链表的两端推入或者弹出元素;根据偏移量对链表进行修剪(trim);读取单个或者多个元素;根据值来查找或者移除元素
Set包含字符串的无序收集器(unorderedcollection),并且被包含的每个字符串都是独一无二的、各不相同添加、获取、移除单个元素;检查一个元素是否存在于某个集合中;计算交集、并集、差集;从集合里卖弄随机获取元素
Hash包含键值对的无序散列表添加、获取、移除单个键值对;获取所有键值对
Zset字符串成员(member)与浮点数分值(score)之间的有序映射,元素的排列顺序由分值的大小决定添加、获取、删除单个元素;根据分值范围(range)或者成员来获取元素

4.3 StringRedisTemplate 与 RedisTemplate

RedisTemplate 对五种数据结构分别定义了操作

  • redisTemplate.opsForValue();

    操作字符串

  • redisTemplate.opsForHash();

    操作hash

  • redisTemplate.opsForList();

    操作list

  • redisTemplate.opsForSet();

    操作set

  • redisTemplate.opsForZSet();

    操作有序set

如果操作字符串的话,建议用 StringRedisTemplate

StringRedisTemplate 与 RedisTemplate 的区别

  1. StringRedisTemplate 继承了 RedisTemplate。

  2. RedisTemplate 是一个泛型类,而 StringRedisTemplate 则不是。

  3. StringRedisTemplate 只能对 key=String,value=String 的键值对进行操作,RedisTemplate 可以对任何类型的 key-value 键值对操作。

  4. 他们各自序列化的方式不同,但最终都是得到了一个字节数组,殊途同归,StringRedisTemplate 使用的是 StringRedisSerializer 类;RedisTemplate 使用的是 JdkSerializationRedisSerializer 类。反序列化,则是一个得到 String,一个得到 Object

  5. 两者的数据是不共通的,StringRedisTemplate 只能管理 StringRedisTemplate 里面的数据,RedisTemplate 只能管理 RedisTemplate中 的数据。

4.4 项目中使用

在需要使用 Redis 的地方,用 @Autowired 注入进来

@Autowired
RedisTemplate redisTemplate;

@Autowired
StringRedisTemplate stringRedisTemplate;

  • 1
  • 2
  • 3
  • 4
  • 5

由于项目中暂时仅用到了 StringRedisTemplate 与 RedisTemplate 的 Hash 结构,StringRedisTemplate 比较简单就不贴代码了,下面仅对操作 Hash 进行举例。

关于 RedisTemplate 的详细用法,有一篇文章已经讲的很细很好了,我觉得没必要再去写了。传送门

用 RedisTemplate 操作 Hash

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 {

<span class="token annotation punctuation">@Autowired</span>
RedisTemplate redisTemplate<span class="token punctuation">;</span>

<span class="token annotation punctuation">@Autowired</span>
LikedService likedService<span class="token punctuation">;</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">saveLiked2Redis</span><span class="token punctuation">(</span>String likedUserId<span class="token punctuation">,</span> String likedPostId<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    String key <span class="token operator">=</span> RedisKeyUtils<span class="token punctuation">.</span><span class="token function">getLikedKey</span><span class="token punctuation">(</span>likedUserId<span class="token punctuation">,</span> likedPostId<span class="token punctuation">)</span><span class="token punctuation">;</span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED<span class="token punctuation">,</span> key<span class="token punctuation">,</span> LikedStatusEnum<span class="token punctuation">.</span>LIKE<span class="token punctuation">.</span><span class="token function">getCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">unlikeFromRedis</span><span class="token punctuation">(</span>String likedUserId<span class="token punctuation">,</span> String likedPostId<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    String key <span class="token operator">=</span> RedisKeyUtils<span class="token punctuation">.</span><span class="token function">getLikedKey</span><span class="token punctuation">(</span>likedUserId<span class="token punctuation">,</span> likedPostId<span class="token punctuation">)</span><span class="token punctuation">;</span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED<span class="token punctuation">,</span> key<span class="token punctuation">,</span> LikedStatusEnum<span class="token punctuation">.</span>UNLIKE<span class="token punctuation">.</span><span class="token function">getCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">deleteLikedFromRedis</span><span class="token punctuation">(</span>String likedUserId<span class="token punctuation">,</span> String likedPostId<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    String key <span class="token operator">=</span> RedisKeyUtils<span class="token punctuation">.</span><span class="token function">getLikedKey</span><span class="token punctuation">(</span>likedUserId<span class="token punctuation">,</span> likedPostId<span class="token punctuation">)</span><span class="token punctuation">;</span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">incrementLikedCount</span><span class="token punctuation">(</span>String likedUserId<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">increment</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED_COUNT<span class="token punctuation">,</span> likedUserId<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">decrementLikedCount</span><span class="token punctuation">(</span>String likedUserId<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">increment</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED_COUNT<span class="token punctuation">,</span> likedUserId<span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> List<span class="token generics function"><span class="token punctuation">&lt;</span>UserLike<span class="token punctuation">&gt;</span></span> <span class="token function">getLikedDataFromRedis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    Cursor<span class="token operator">&lt;</span>Map<span class="token punctuation">.</span>Entry<span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span><span class="token operator">&gt;</span> cursor <span class="token operator">=</span> redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">scan</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED<span class="token punctuation">,</span> ScanOptions<span class="token punctuation">.</span>NONE<span class="token punctuation">)</span><span class="token punctuation">;</span>
    List<span class="token generics function"><span class="token punctuation">&lt;</span>UserLike<span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>cursor<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
        Map<span class="token punctuation">.</span>Entry<span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span> entry <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        String key <span class="token operator">=</span> <span class="token punctuation">(</span>String<span class="token punctuation">)</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//分离出 likedUserId,likedPostId</span>
        String<span class="token punctuation">[</span><span class="token punctuation">]</span> split <span class="token operator">=</span> key<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">"::"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        String likedUserId <span class="token operator">=</span> split<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
        String likedPostId <span class="token operator">=</span> split<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
        Integer value <span class="token operator">=</span> <span class="token punctuation">(</span>Integer<span class="token punctuation">)</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//组装成 UserLike 对象</span>
        UserLike userLike <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">UserLike</span><span class="token punctuation">(</span>likedUserId<span class="token punctuation">,</span> likedPostId<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
        list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>userLike<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//存到 list 后从 Redis 中删除</span>
        redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> list<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> List<span class="token generics function"><span class="token punctuation">&lt;</span>LikedCountDTO<span class="token punctuation">&gt;</span></span> <span class="token function">getLikedCountFromRedis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
    Cursor<span class="token operator">&lt;</span>Map<span class="token punctuation">.</span>Entry<span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span><span class="token operator">&gt;</span> cursor <span class="token operator">=</span> redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">scan</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED_COUNT<span class="token punctuation">,</span> ScanOptions<span class="token punctuation">.</span>NONE<span class="token punctuation">)</span><span class="token punctuation">;</span>
    List<span class="token generics function"><span class="token punctuation">&lt;</span>LikedCountDTO<span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>cursor<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span>
        Map<span class="token punctuation">.</span>Entry<span class="token generics function"><span class="token punctuation">&lt;</span>Object<span class="token punctuation">,</span> Object<span class="token punctuation">&gt;</span></span> map <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//将点赞数量存储在 LikedCountDT</span>
        String key <span class="token operator">=</span> <span class="token punctuation">(</span>String<span class="token punctuation">)</span> map<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        LikedCountDTO dto <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LikedCountDTO</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> <span class="token punctuation">(</span>Integer<span class="token punctuation">)</span> map<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>dto<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//从Redis中删除这条记录</span>
        redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>RedisKeyUtils<span class="token punctuation">.</span>MAP_KEY_USER_LIKED_COUNT<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> list<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98

五、Redis 实现分布式锁

讲完了基础操作,再说个实战运用,用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> 
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • GETSET

    自动将key对应到value并且返回原来key对应的value。如果key存在但是对应的value不是字符串,就返回错误。

    设计模式

    GETSET可以和INCR一起使用实现支持重置的计数功能。举个例子:每当有事件发生的时候,一段程序都会调用INCR给key mycounter加1,但是有时我们需要获取计数器的值,并且自动将其重置为0。这可以通过GETSET mycounter “0”来实现:

    INCR mycounter
    GETSET mycounter "0"
    GET mycounter
    
       
    • 1
    • 2
    • 3

    返回值

    bulk-string-reply: 返回之前的旧值,如果之前Key不存在将返回nil

    例子

    redis> INCR mycounter
    (integer) 1
    redis> GETSET mycounter "0"
    "1"
    redis> GET mycounter
    "0"
    redis>
    
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

这两个命令在 java 中对应为 setIfAbsentgetAndSet

分布式锁的实现:

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 {

<span class="token annotation punctuation">@Autowired</span>
StringRedisTemplate redisTemplate<span class="token punctuation">;</span>

<span class="token comment">/**
 * 加锁
 * @param key
 * @param value 当前时间 + 超时时间
 * @return
 */</span>
<span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">lock</span><span class="token punctuation">(</span>String key<span class="token punctuation">,</span> String value<span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setIfAbsent</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">//解决死锁,且当多个线程同时来时,只会让一个线程拿到锁</span>
    String currentValue <span class="token operator">=</span> redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//如果过期</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>StringUtils<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span>currentValue<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
            Long<span class="token punctuation">.</span><span class="token function">parseLong</span><span class="token punctuation">(</span>currentValue<span class="token punctuation">)</span> <span class="token operator">&lt;</span> System<span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
        <span class="token comment">//获取上一个锁的时间</span>
        String oldValue <span class="token operator">=</span> redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getAndSet</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>StringUtils<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span>oldValue<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> oldValue<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>currentValue<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">/**
 * 解锁
 * @param key
 * @param value
 */</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">unlock</span><span class="token punctuation">(</span>String key<span class="token punctuation">,</span> String value<span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>

    <span class="token keyword">try</span> <span class="token punctuation">{<!-- --></span>
        String currentValue <span class="token operator">=</span> redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>StringUtils<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span>currentValue<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> currentValue<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
            redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getOperations</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"【redis锁】解锁失败, {}"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

使用:


/**
 * 模拟秒杀
 */
public class SecKillService {
<span class="token annotation punctuation">@Autowired</span>
RedisLock redisLock<span class="token punctuation">;</span>

<span class="token comment">//超时时间10s</span>
<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> TIMEOUT <span class="token operator">=</span> <span class="token number">10</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">secKill</span><span class="token punctuation">(</span>String productId<span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
    <span class="token keyword">long</span> time <span class="token operator">=</span> System<span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> TIMEOUT<span class="token punctuation">;</span>
    <span class="token comment">//加锁</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>redisLock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span>productId<span class="token punctuation">,</span> String<span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>time<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">SellException</span><span class="token punctuation">(</span><span class="token number">101</span><span class="token punctuation">,</span> <span class="token string">"人太多了,等会儿再试吧~"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">//具体的秒杀逻辑</span>

    <span class="token comment">//解锁</span>
    redisLock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span>productId<span class="token punctuation">,</span> String<span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>time<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

更多 Redis 的具体使用场景请关注开源项目 CodeRiver,致力于打造全平台型全栈精品开源项目。

coderiver 中文名 河码,是一个为程序员和设计师提供项目协作的平台。无论你是前端、后端、移动端开发人员,或是设计师、产品经理,都可以在平台上发布项目,与志同道合的小伙伴一起协作完成项目。

coderiver河码 类似程序员客栈,但主要目的是方便各细分领域人才之间技术交流,共同成长,多人协作完成项目。暂不涉及金钱交易。

计划做成包含 pc端(Vue、React)、移动H5(Vue、React)、ReactNative混合开发、Android原生、微信小程序、java后端的全平台型全栈项目,欢迎关注。

项目地址:https://github.com/cachecats/coderiver


您的鼓励是我前行最大的动力,欢迎点赞,欢迎送小星星✨ ~

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值