常用操作
public class RedisTest{ @Resource private StringRedisTemplate stringRedisTemplate; public void testRedisList(){ List<String> skuIds = new ArrayList<>(); // 往redis中存入整个List<String> stringRedisTemplate.opsForList().leftPushAll("gulimall:seckill:sessions:12345", skuIds); // 获取redis中所有指定格式的key, * 代表不确定的字符 Set<String> keys = stringRedisTemplate.keys("gulimall:seckill:sessions:" + "*"); // 取出redis的list中索引从-100到100的所有值 List<String> skuIds = stringRedisTemplate.opsForList().range("gulimall:seckill:sessions:12345", -100, 100); } public void testRedisHash(){ // 绑定Redis的Hash,准备Hash操作 BoundHashOperations<String, String, String> skusOperations = stringRedisTemplate .boundHashOps("gulimall:seckill:skus"); // 存入数据,k、v都得是String类型 skusOperations.put(relation.getSkuId().toString(), jsonStr); // 从Hash中批量获取多个key的值 List<String> values = skusOperations.multiGet(skuIds); } public void testRedisAbsent(){ // 尝试在Redis中占位 Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent("123_456_789", "1000", 145632549L, TimeUnit.MILLISECONDS); } }
存储获取缓存值
RedisKeyUtil.java
/* * 首页猜你喜欢商品集合 * * @param regionCode * @return */ public static String getGuessYouLikeProductsKey(Integer regionCode) { return MessageFormat.format("{0}:home:like:product:{1}", PROJECT_SPACE, String.valueOf(regionCode)); }
RetailHomeServiceImpl.java
@Resource private RedisService redisService; private List<Long> getProductIds(List<Long> mchIds, String key) { String key = RedisKeyUtil.getGuessYouLikeProductsKey(regionCode); String jsonString = redisService.get(key); List<Long> productIds; if (StringUtils.isNotEmpty(jsonString)) { // 缓存不为空,直接取缓存 productIds = JSON.parseObject(jsonString, new TypeReference<List<Long>>() { }); } else { // 缓存为空,则重新查询 productIds = retailProductService.getRandomProductIds(mchIds); // 要缓存的值 String redisValue = JSON.toJSONString(productIds); // 存入redis redisService.set(key, redisValue, RetailPortalConstant.ORDER_TIMEOUT_PAY, TimeUnit.MINUTES); } return productIds; }
分布式锁
配置类
@Configurationpublic class RedissonConfig { /** * 所有对Redisson的使用都是通过RedissonClient对象 * @return */ @Bean(destroyMethod = "shutdown") // 服务停止以后,会调用shutdown进行销毁 RedissonClient redission() { Config config = new Config(); config.useSingleServer().setAddress("redis://192.168.2.190:6379"); return Redisson.create(config); }}
使用
public class RedissonTest{ @Resource private RedissonClient redissonClient; public void test1(){ // 为了限流:使用秒杀商品的库存作为分布式的信号量 RSemaphore semaphore = redissonClient.getSemaphore("gulimall:seckill:semaphore:11984846"); // 为信号量设置值 semaphore.trySetPermits(relation.getSeckillCount()); // 让信号量尝试扣减值 try { // 要扣的数量,等待的时间,时间单位 boolean acquire = semaphore.tryAcquire(1, 100, TimeUnit.MILLISECONDS); if (acquire) { // 扣减成功 } } catch (InterruptedException e) { e.printStackTrace(); } }}