package com.learn.api.controller;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.learn.base.BaseApiService;
import com.learn.base.BaseRedisService;
import com.learn.base.ResponseBase;
@RestController
public class PayController extends BaseApiService {
@Autowired
private BaseRedisService baseRedisService;
private static final Long TOKENTIME = (long) (30 * 60);
// 先获取参数接口,返回令牌
// 使用令牌传递参数 (不是前端调用是服务器调用)
@RequestMapping("/getPayToken")
public String getPayToken(Long userId, Long money) {
// 生成令牌
String payToken = UUID.randomUUID().toString();
// 存放在redis中
baseRedisService.setString(payToken, userId + "---" + money, TOKENTIME);
return payToken;
}
@RequestMapping("/pay")
public ResponseBase pay(String payToken) {
if (StringUtils.isEmpty(payToken)) {
return setResultError("token 不能为空!");
}
String result = (String) baseRedisService.getString(payToken);
if (StringUtils.isEmpty(result)) {
return setResultError("参数不能为空!");
}
// 直接处理操作数据库
return setResultSuccessData(result);
}
}
package com.learn.base;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class BaseRedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setString(String key, Object data, Long timeout) {
if (data instanceof String) {
String value = (String) data;
stringRedisTemplate.opsForValue().set(key, value);
}
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
}
public Object getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void delKey(String key) {
stringRedisTemplate.delete(key);
}
}
localhost:8080/getPayToken?userId=1&money=10
071b08e9-8fd7-4f54-8005-db05481d1030
localhost:8080/pay?payToken=071b08e9-8fd7-4f54-8005-db05481d1030
{
rtnCode: 200,
msg: "success",
data: "1---10"
}