redis 事物限制频率和获得令牌

package com.dongnaoedu.tony.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

@Component
public class MiaoshaService {

private final Logger logger = LoggerFactory.getLogger(MiaoshaService.class);

@Autowired
StringRedisTemplate stringRedisTemplate;

@Autowired
DatabaseService databaseService;

/**
* 秒杀具体实现
*
* @param goodsCode
* 商品编码
* @param userId
* 用户ID
* @return
*/
public boolean miaosha(String goodsCode, final String userId) {
// 方案3: 频率限制
// 用户操作频率限制,5秒内允许访问一次
// set setnx setex
boolean value = stringRedisTemplate.execute(new RedisCallback<Boolean>() {

@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
Boolean result = connection.set(userId.getBytes(), "".getBytes(), Expiration.milliseconds(10000L),
SetOption.SET_IF_ABSENT);
return result;
}
});
if (!value) {
System.out.println("被限制操作频率啦,用户:" + userId);
return false;
}

// 方案4: 令牌机制
// 取令牌,拿到令牌的允许尝试购买
String token = stringRedisTemplate.opsForList().leftPop("token_list");
if (token == null || "".equals(token)) {
System.out.println("没抢到Token,不参与秒杀,用户:" + userId);
return false;
}

boolean result = databaseService.buy(goodsCode, userId);
System.out.println("秒杀结果:" + result);
return result;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值