redis在高并发时的正确使用

redis在高并发时的正确使用

1.初始版本:redis在正常项目中的使用逻辑

1.新增时将对应的数据存储到redis中
2.修改时重新更改redis对应数据
3.获取时先从redis中获取,没有的话再从数据库中获取
//redis配置
 
package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 *
 */
@Configuration
public class RedisConfig {
  @Bean
  @SuppressWarnings("all")
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringRedisSerializer);
    template.setHashKeySerializer(stringRedisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
  }
}

package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 */
@Component
public final class RedisUtil {

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;

  /**
   * 指定缓存失效时间
   *
   * @param key  键
   * @param time 时间(秒)
   * @return true 成功 false 失败
   */
  public boolean expire(String key, long time) {
    try {
      if (time > 0) {
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 根据key 获取过期时间
   *
   * @param key 键 不能为null
   * @return 时间(秒) 返回0代表为永久有效
   */
  public long getExpire(String key) {
    return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  }

  /**
   * 判断key是否存在
   *
   * @param key 键
   * @return true 存在 false不存在
   */
  public boolean hasKey(String key) {
    try {
      return redisTemplate.hasKey(key);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 删除缓存
   *
   * @param key 可以传一个值 或多个
   */
  @SuppressWarnings("unchecked")
  public void del(String... key) {
    if (key != null && key.length > 0) {
      if (key.length == 1) {
        redisTemplate.delete(key[0]);
      } else {
        redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
      }
    }
  }

  // ============================String=============================

  /**
   * 普通缓存获取
   *
   * @param key 键
   * @return 值
   */
  public Object get(String key) {
    return key == null ? null : redisTemplate.opsForValue().get(key);
  }

  public <T> T get(String key, Class<T> clazz) {
    Object obj = key == null ? null : redisTemplate.opsForValue().get(key);
    if (clazz.isInstance(obj)) {
      return clazz.cast(obj);
    }
    return null;
  }

  /**
   * 普通缓存放入
   *
   * @param key   键
   * @param value 值
   * @return true成功 false失败
   */
  public boolean set(String key, Object value) {
    try {
      redisTemplate.opsForValue().set(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }


  /**
   * 普通缓存放入并设置时间
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
   * @return true成功 false 失败
   */
  public boolean set(String key, Object value, long time) {
    try {
      if (time > 0) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
      } else {
        set(key, value);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }

  /**
   * 如果key已存在就不执行,并返回false 不存在就执行 并返回true
   *
   * @param key
   * @param value
   * @return true成功 false失败
   */
  public Boolean setNx(String key, Object value) {
    return redisTemplate.opsForValue().setIfAbsent(key, value);
  }

  /**
   * 如果key已存在就不执行,并返回false 不存在就执行 并返回true
   *
   * @param key
   * @param value
   * @return true成功 false失败
   */
  public Boolean setNx(String key, Object value, long time) {
    return redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
  }


  /**
   * 如果key已存在就执行,并返回true 不存在就不执行 并返回false
   *
   * @param key
   * @param value
   * @return true成功 false失败
   */
  public Boolean setXx(String key, Object value) {
    return redisTemplate.opsForValue().setIfPresent(key, value);
  }

  /**
   * 如果key已存在就执行,并返回true 不存在就不执行 并返回false
   *
   * @param key
   * @param value
   * @return true成功 false失败
   */
  public Boolean setXx(String key, Object value, long time) {
    return redisTemplate.opsForValue().setIfPresent(key, value, time, TimeUnit.SECONDS);

  }

  /**
   * 递增
   *
   * @param key   键
   * @param delta 要增加几(大于0)
   * @return
   */
  public long incr(String key, long delta) {
    if (delta < 0) {
      throw new RuntimeException("递增因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, delta);
  }

  /**
   * 递减
   *
   * @param key   键
   * @param delta 要减少几(小于0)
   * @return
   */
  public long decr(String key, long delta) {
    if (delta < 0) {
      throw new RuntimeException("递减因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, -delta);
  }

  // ================================Map=================================

  /**
   * HashGet
   *
   * @param key  键 不能为null
   * @param item 项 不能为null
   * @return 值
   */
  public Object hget(String key, String item) {
    return redisTemplate.opsForHash().get(key, item);
  }

  /**
   * 获取hashKey对应的所有键值
   *
   * @param key 键
   * @return 对应的多个键值
   */
  public Map<Object, Object> hmget(String key) {
    return redisTemplate.opsForHash().entries(key);
  }

  /**
   * HashSet
   *
   * @param key 键
   * @param map 对应多个键值
   * @return true 成功 false 失败
   */
  public boolean hmset(String key, Map<String, Object> map) {
    try {
      redisTemplate.opsForHash().putAll(key, map);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * HashSet 并设置时间
   *
   * @param key  键
   * @param map  对应多个键值
   * @param time 时间(秒)
   * @return true成功 false失败
   */
  public boolean hmset(String key, Map<String, Object> map, long time) {
    try {
      redisTemplate.opsForHash().putAll(key, map);
      if (time > 0) {
        expire(key, time);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 向一张hash表中放入数据,如果不存在将创建
   *
   * @param key   键
   * @param item  项
   * @param value 值
   * @return true 成功 false失败
   */
  public boolean hset(String key, String item, Object value) {
    try {
      redisTemplate.opsForHash().put(key, item, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 向一张hash表中放入数据,如果不存在将创建
   *
   * @param key   键
   * @param item  项
   * @param value 值
   * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
   * @return true 成功 false失败
   */
  public boolean hset(String key, String item, Object value, long time) {
    try {
      redisTemplate.opsForHash().put(key, item, value);
      if (time > 0) {
        expire(key, time);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 删除hash表中的值
   *
   * @param key  键 不能为null
   * @param item 项 可以使多个 不能为null
   */
  public void hdel(String key, Object... item) {
    redisTemplate.opsForHash().delete(key, item);
  }

  /**
   * 判断hash表中是否有该项的值
   *
   * @param key  键 不能为null
   * @param item 项 不能为null
   * @return true 存在 false不存在
   */
  public boolean hHasKey(String key, String item) {
    return redisTemplate.opsForHash().hasKey(key, item);
  }

  /**
   * hash递增 如果不存在,就会创建一个 并把新增后的值返回
   *
   * @param key  键
   * @param item 项
   * @param by   要增加几(大于0)
   * @return
   */
  public double hincr(String key, String item, double by) {
    return redisTemplate.opsForHash().increment(key, item, by);
  }

  /**
   * hash递减
   *
   * @param key  键
   * @param item 项
   * @param by   要减少记(小于0)
   * @return
   */
  public double hdecr(String key, String item, double by) {
    return redisTemplate.opsForHash().increment(key, item, -by);
  }

  // ============================set=============================

  /**
   * 根据key获取Set中的所有值
   *
   * @param key 键
   * @return
   */
  public Set<Object> sGet(String key) {
    try {
      return redisTemplate.opsForSet().members(key);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 根据value从一个set中查询,是否存在
   *
   * @param key   键
   * @param value 值
   * @return true 存在 false不存在
   */
  public boolean sHasKey(String key, Object value) {
    try {
      return redisTemplate.opsForSet().isMember(key, value);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 将数据放入set缓存
   *
   * @param key    键
   * @param values 值 可以是多个
   * @return 成功个数
   */
  public long sSet(String key, Object... values) {
    try {
      return redisTemplate.opsForSet().add(key, values);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  /**
   * 将set数据放入缓存
   *
   * @param key    键
   * @param time   时间(秒)
   * @param values 值 可以是多个
   * @return 成功个数
   */
  public long sSetAndTime(String key, long time, Object... values) {
    try {
      Long count = redisTemplate.opsForSet().add(key, values);
      if (time > 0)
        expire(key, time);
      return count;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  /**
   * 获取set缓存的长度
   *
   * @param key 键
   * @return
   */
  public long sGetSetSize(String key) {
    try {
      return redisTemplate.opsForSet().size(key);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  /**
   * 移除值为value的
   *
   * @param key    键
   * @param values 值 可以是多个
   * @return 移除的个数
   */
  public long setRemove(String key, Object... values) {
    try {
      Long count = redisTemplate.opsForSet().remove(key, values);
      return count;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }
  // ===============================list=================================

  /**
   * 获取list缓存的内容
   *
   * @param key   键
   * @param start 开始
   * @param end   结束 0 到 -1代表所有值
   * @return
   */
  public List<Object> lGet(String key, long start, long end) {
    try {
      return redisTemplate.opsForList().range(key, start, end);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 获取list缓存的长度
   *
   * @param key 键
   * @return
   */
  public long lGetListSize(String key) {
    try {
      return redisTemplate.opsForList().size(key);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  /**
   * 通过索引 获取list中的值
   *
   * @param key   键
   * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
   * @return
   */
  public Object lGetIndex(String key, long index) {
    try {
      return redisTemplate.opsForList().index(key, index);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @return
   */
  public boolean lSet(String key, Object value) {
    try {
      redisTemplate.opsForList().rightPush(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒)
   * @return
   */
  public boolean lSet(String key, Object value, long time) {
    try {
      redisTemplate.opsForList().rightPush(key, value);
      if (time > 0)
        expire(key, time);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @return
   */
  public boolean lSet(String key, List<Object> value) {
    try {
      redisTemplate.opsForList().rightPushAll(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒)
   * @return
   */
  public boolean lSet(String key, List<Object> value, long time) {
    try {
      redisTemplate.opsForList().rightPushAll(key, value);
      if (time > 0)
        expire(key, time);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 根据索引修改list中的某条数据
   *
   * @param key   键
   * @param index 索引
   * @param value 值
   * @return
   */
  public boolean lUpdateIndex(String key, long index, Object value) {
    try {
      redisTemplate.opsForList().set(key, index, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 移除N个值为value
   *
   * @param key   键
   * @param count 移除多少个
   * @param value 值
   * @return 移除的个数
   */
  public long lRemove(String key, long count, Object value) {
    try {
      Long remove = redisTemplate.opsForList().remove(key, count, value);
      return remove;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }
}




//实体类
@Data
public class Product implements Serializable {
    private String id;
    private String name;
    private String price;
}

//controller层
@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("getById")
    public Product get(String productId) {
        return productService.getById(productId);
    }

    @RequestMapping("add")
    public int add(Product product) {
        return productService.add(product);
    }
    
    @RequestMapping("update")
    public int update(Product product) {
        return productService.updateProduct(product);
    }
}

//service层
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
@Service
public class ProductService extends ServiceImpl<ProductMapper, Product> {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private ProductMapper productMapper;

    public static final String PRODUCT_KEY = "product:";
    
    public Product getById(String productId) {
        Product product;
        String json = redisUtil.get(PRODUCT_KEY + productId, String.class);
        if (StrUtil.isNotEmpty(json)) {
            redisUtil.set(PRODUCT_KEY + productId, json);
            return JSONUtil.toBean(json, Product.class);
        }
        product = productMapper.selectById(productId);
        redisUtil.set(PRODUCT_KEY + productId, json);
        return product;
    }

    public int add(Product product) {
        String productId = UUID.randomUUID().toString();
        product.setId(productId);
        int i = productMapper.insert(product);
        redisUtil.set(PRODUCT_KEY+productId, JSONUtil.toJsonStr(product));
        return i;
    }

    public int updateProduct(Product product) {
        int i = productMapper.updateById(product);
        redisUtil.set(PRODUCT_KEY+product.getId(), JSONUtil.toJsonStr(product));
        return i;
    }
}
//mapper层
@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}

2.解决数据过多问题

**问题: **过量的热点数据, 可能只使用了一次就存到了redis中, 数据量过多后占用内存

**解决: **给对应的数据加个过期时间, 并在下次查询时更新过期时间

//service中
public Product getById(String productId) {
    Product product;
    String json = redisUtil.get(PRODUCT_KEY + productId, String.class);
    if (StrUtil.isNotEmpty(json)) {
        //增加一个过期时间
        redisUtil.set(PRODUCT_KEY + productId, json,3600);
        return JSONUtil.toBean(json, Product.class);
    }
    product = productMapper.selectById(productId);
     //增加一个过期时间
    redisUtil.set(PRODUCT_KEY + productId, json,3600);
    return product;
}

public int add(Product product) {
    String productId = UUID.randomUUID().toString();
    product.setId(productId);
    int i = productMapper.insert(product);
      //增加一个过期时间
    redisUtil.set(PRODUCT_KEY+productId, JSONUtil.toJsonStr(product),3600);
    return i;
}

public int updateProduct(Product product) {
    int i = productMapper.updateById(product);
     //增加一个过期时间
    redisUtil.set(PRODUCT_KEY + product.getId(), JSONUtil.toJsonStr(product),3600);
    return i;
}

3.解决缓存穿透问题

**问题:**在通过id查询过程中 ,如果redis没有,查询数据库,数据库也没有,这时候又一直查询,数据库压力大

**解决:**在查询数据库后如果没有查到可以放一个空的字符串

public static final String EMPTY_STR="{}";
public Product getById(String productId) {
    Product product;
    String json = redisUtil.get(PRODUCT_KEY + productId, String.class);
    if (StrUtil.isNotEmpty(json)) {
        //增加判断是否为空字符串
        if (EMPTY_STR.equals(json)) {
            return new Product();
        }
        redisUtil.set(PRODUCT_KEY + productId, json, 3600);
        return JSONUtil.toBean(json, Product.class);
    }
    product = productMapper.selectById(productId);
    //如果查出数据库为空 直接赋值为空字符串
    if (product == null) {
        redisUtil.set(PRODUCT_KEY + productId, EMPTY_STR, 3600);
    }else{
        redisUtil.set(PRODUCT_KEY + productId, JSONUtil.toJsonStr(product), 3600);
    }
    return product;
}

4.解决商品突然为热点数据问题

**问题:**如果某个商品突然变为热点数据,比如直播时把他突然变为热卖品,这时redis没有,大量请求访问数据库

**解决:**使用分布式事务锁redis的setnx (Redisson) 并再进行一次查询redis数据

<!--引入redisson --> 
<dependency>
     <groupId>org.redisson</groupId>
     <artifactId>redisson</artifactId>
     <version>3.16.6</version>
</dependency>
//修改RedisConfig类,增加redisson配置
package com.example.demo.config;


import org.redisson.config.Config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 *
 */
@Configuration
public class RedisConfig {

  @Value("${spring.redis.host}")
  private String host;
  @Value("${spring.redis.port}")
  private String port;
  @Value("${spring.redis.password}")
  private String password;

  @Bean
  public Redisson redisson() {
    Config config = new Config();
    String address = new StringBuilder("redis://").append(host).append(":").append(port).toString();
    config.useSingleServer().setAddress(address);
    if (null != password && !"".equals(password.trim())) {
      config.useSingleServer().setPassword(password);
    }
    return (Redisson) Redisson.create(config);
  }
..................................   

}
//service层中
@Autowired
private Redisson redisson;
public static final String LOCK_HOT_CACHE = "lock:hot_cache:";

public Product getById(String productId) {
    Product product;
    String json = redisUtil.get(PRODUCT_KEY + productId, String.class);
    if (StrUtil.isNotEmpty(json)) {
        if (EMPTY_STR.equals(json)) {
            return new Product();
        }
        redisUtil.set(PRODUCT_KEY + productId, json, 3600);
        return JSONUtil.toBean(json, Product.class);
    }
    //1.首先使用分布式锁(作用是保证请求是一个一个进来的)
    RLock lock = redisson.getLock(LOCK_HOT_CACHE + productId);
    lock.lock();//相当于setnx(key)
    //2.重新查询redis看缓存(确保后面几次进来后不需要继续查询数据库)
    //try finally是为了保证成功释放锁
    try {
        json = redisUtil.get(PRODUCT_KEY + productId, String.class);
        if (StrUtil.isNotEmpty(json)) {
            if (EMPTY_STR.equals(json)) {
                return new Product();
            }
            redisUtil.set(PRODUCT_KEY + productId, json, 3600);
            return JSONUtil.toBean(json, Product.class);
        }
        product = productMapper.selectById(productId);
        if (product == null) {
            redisUtil.set(PRODUCT_KEY + productId, EMPTY_STR, 3600);
        }else{
            redisUtil.set(PRODUCT_KEY + productId, JSONUtil.toJsonStr(product), 3600);
        }
    } finally {
        //3.释放锁
        lock.unlock();//del(key)
    }
    return product;
}

5.解决代码冗余问题

**问题:**代码冗余

//service中
public Product getById(String productId) {
    Product product;
    Product product1 = getProductFromCache(productId);
    if (product1 != null) {
        return product1;
    }
    //1.首先使用分布式锁(作用是保证请求是一个一个进来的)
    RLock lock = redisson.getLock(PRODUCT_KEY + productId);
    lock.lock();//相当于setnx()
    //2.重新查询redis看缓存(确保后面几次进来后不需要继续查询数据库)
    try {
        product1 = getProductFromCache(productId);
        if (product1 != null) {
            return product1;
        }
        product = productMapper.selectById(productId);
        if (product == null) {
            redisUtil.set(PRODUCT_KEY + productId, EMPTY_STR, 3600);
        } else {
            redisUtil.set(PRODUCT_KEY + productId, JSONUtil.toJsonStr(product), 3600);
        }
    } finally {
        //3.释放锁
        lock.unlock();
    }
    return product;
}
private Product getProductFromCache(String productId) {
    Product product = null;
    String json = redisUtil.get(PRODUCT_KEY + productId, String.class);
    if (StrUtil.isNotEmpty(json)) {
        if (EMPTY_STR.equals(json)) {
            product = new Product();
        }
        redisUtil.set(PRODUCT_KEY + productId, json, 3600);
        product = JSONUtil.toBean(json, Product.class);
    }
    return product;
}

6.解决多线程下双写不一致问题

**问题:**有两个线程,第一个线程查缓存为空,查数据库为10;此时第二个线程修改数据库为20,更新缓存;第一个线程这时更新缓存为10,数据有误

**解决:**分布式事务锁, 在多种情况下更新redis时加上锁

public static final String UPDATE_PRODUCT = "lock:update_product:";

public Product getById(String productId) {
    Product product;
    Product product1 = getProductFromCache(productId);
    if (product1 != null) {
        return product1;
    }
    RLock lock = redisson.getLock(LOCK_HOT_CACHE + productId);
    lock.lock();//相当于setnx()
    try {
        product1 = getProductFromCache(productId);
        if (product1 != null) {
            return product1;
        }
        //加一个update时的分布式锁
        RLock updateProductLock = redisson.getLock(UPDATE_PRODUCT + productId);
        updateProductLock.lock();
        try {
            product = productMapper.selectById(productId);
            if (product == null) {
                redisUtil.set(PRODUCT_KEY + productId, EMPTY_STR, 3600);
            } else {
                redisUtil.set(PRODUCT_KEY + productId, JSONUtil.toJsonStr(product), 3600);
            }
        } finally {
            //释放锁
            updateProductLock.unlock();
        }
    } finally {
        lock.unlock();
    }
    return product;
}

 public int updateProduct(Product product) {
     //更新时也需要这把锁
     RLock updateProductLock = redisson.getLock(UPDATE_PRODUCT + product.getId());
     updateProductLock.lock();
     int i;
     try {
         i = productMapper.updateById(product);
         redisUtil.set(PRODUCT_KEY + product.getId(), JSONUtil.toJsonStr(product), 3600);
     } finally {
         updateProductLock.unlock();
     }
     return i;
 }

7.解决分布式锁的串行性能问题

**问题:**加了很多分布式事务锁,对于同一个产品会有性能问题

**解决:**1.在getById时大部分都是读操作,只有在update时才是写操作,可以使用redisson的读写锁,

​ 2.在getByid时,可以使用tryLock()来直接结束锁,不再让其他线程一次加锁放锁

public Product getById(String productId) {
    Product product;
    Product product1 = getProductFromCache(productId);
    if (product1 != null) {
        return product1;
    }
    RLock lock = redisson.getLock(LOCK_HOT_CACHE + productId);
    //将这里改为trylock,它的意思是第一个线程持锁就3秒(3秒是评估业务下面能走完,redis中一定有数据了),然后就不再有锁,后面的线程也不会再加锁和释放锁
    lock.tryLock(3, TimeUnit.SECONDS);
    //lock.lock();//相当于setnx()
    try {
        product1 = getProductFromCache(productId);
        if (product1 != null) {
            return product1;
        }
        //在getByid中加一个读锁
        RReadWriteLock readWriteLock = redisson.getReadWriteLock(UPDATE_PRODUCT + productId);
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        try {
            product = productMapper.selectById(productId);
            if (product == null) {
                redisUtil.set(PRODUCT_KEY + productId, EMPTY_STR, 3600);
            } else {
                redisUtil.set(PRODUCT_KEY + productId, JSONUtil.toJsonStr(product), 3600);
            }
        } finally {
          
            rLock.unlock();
        }
    } finally {
        //释放锁
        lock.unlock();
    }
    return product;
}

public int updateProduct(Product product) {
    //在更新时加一个写锁
    RReadWriteLock readWriteLock = redisson.getReadWriteLock(UPDATE_PRODUCT + product.getId());
    RLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    int i;
    try {
        i = productMapper.updateById(product);
        redisUtil.set(PRODUCT_KEY + product.getId(), JSONUtil.toJsonStr(product), 3600);
    } finally {
        writeLock.unlock();
    }
    return i;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值