欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用redis锁防止表单重复提交

程序员文章站 2022-05-06 18:18:51
...


使用redis锁防止表单重复提交

模拟表单重复提交

package examples;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class StudentTest {
	public static void main(String[] args) {
        //创建可关闭的客户端工具
        CloseableHttpClient c1 = HttpClients.createDefault();
        CloseableHttpClient c2 = HttpClients.createDefault();

        HttpPost r1 = new HttpPost("http://192.168.18.107:8080/stu/list/save");
        HttpPost r2 = new HttpPost("http://192.168.18.107:8080/stu/list/save");

        String data = "sno=&sname=%E5%BC%A0%E4%B8%89&gender=1&birth=2020-06-08&phone=17721038957&photoUrl=%2Fimg%2Fdefault.png";

        StringEntity requestEntity = new StringEntity(data,"utf-8");

        r1.addHeader("Content-type","application/x-www-form-urlencoded");
        r1.addHeader("Cookie","JSESSIONID=0a2e441b-6560-40d9-beef-88a555b426df");
        r1.setEntity(requestEntity);

        r2.addHeader("Content-type","application/x-www-form-urlencoded");
        r2.addHeader("Cookie","JSESSIONID=0a2e441b-6560-40d9-beef-88a555b426df");
        r2.setEntity(requestEntity);

        Thread t1 = new MyThread(c1,r1);
        Thread t2 = new MyThread(c2,r2);

        t1.start();
        t2.start();
        //c1.close();
        //c2.close();
        //System.out.println("Hello World!");
	}
}


package examples;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

public class MyThread extends Thread {
    private CloseableHttpClient client;
    private HttpPost request;

    public MyThread(CloseableHttpClient client, HttpPost request) {
        this.client = client;
        this.request = request;
    }

    public void run(){
        try {
            HttpResponse response = client.execute(request);
            String text = EntityUtils.toString(response.getEntity());
            System.out.println(Thread.currentThread().getName()+": "+text);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

学生保存接口

    /**
     * 学生保存
     * @param stu
     * @return
     */
    @Log("保存学生")
    @ApiOperation(value = "学生信息保存", notes = "将输入的学生信息保存到数据库")
    @PostMapping(value = "/save", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ActionResult saveStudent(StudentDO stu){
        ActionResult result = new ActionResult();

        if(stu.getSno()==null){
            String lockKey = "student:phone:"+stu.getPhone();
            RLock lock = redissonClient.getLock(lockKey);
            boolean res = false;
            try {
                //获取锁等待超时时间为5s,锁租期为60s
                res = lock.tryLock(5, 60, TimeUnit.SECONDS);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            if (!res) {
                logger.info("获取锁超时 res: {}", res);
                result.setStatus(-2);
                result.setMsg("该学生正在新增中,请稍后再试...");
                return result;
            }

            try {
                List<StudentDO> list = studentDOMapper.selectByPhone(stu.getPhone());
                if(list!=null&&list.size()>0){
                    result = ActionResult.build(-1, "手机号码重复,添加失败");
                    return result;
                }
                studentDOMapper.insert(stu);
            } finally {
                //超过leaseTime锁自动释放,导致unlock方法失效
                try {
                    if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                        lock.unlock();
                        logger.info("释放锁");
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }

        } else {
            List<StudentDO> list = studentDOMapper.selectByPhoneAndSno(stu.getPhone(), stu.getSno());
            if(list!=null&&list.size()>0){
                result = ActionResult.build(-1, "手机号码重复,修改失败");
                return result;
            }
            studentDOMapper.updateByPrimaryKey(stu);
        }
        result = ActionResult.ok(studentDOMapper.selectByPrimaryKey(stu.getSno()));
        return result;
    }

项目开源地址

https://github.com/yangzc23/studentboot

参考资料
[01] 使用Session防止表单重复提交
[02] JavaWeb防止表单重复提交的几种方式
[03] Redisson基本用法
[04] redis客户端redisson实战
[05] HttpClient 4 使用POST方式提交普通表单数据的例子

微信扫一扫关注公众号
使用redis锁防止表单重复提交
点击链接加入群聊

https://jq.qq.com/?_wv=1027&k=5eVEhfN
软件测试学习交流QQ群号:511619105

相关标签: 05软件开发