Java 多线程发起 http 请求

  1. 创建线程类,继承 Tread 类
package com.example.header1.utils;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.sql.Time;

/**
 * @Description
 * @Author jimaomao
 * @DATE 2024/3/12 10:19
 */
public class MyThread extends Thread{

    private String name;


    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8081";
        String api = url + "/hello?name=" + this.name;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(api, String.class);
        String responseEntityBody = responseEntity.getBody();
        System.out.println(responseEntityBody);
    }
}

  1. 创建对象,启动线程
package com.example.header1.demos.web;

import com.example.header1.utils.MyThread;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Controller
public class BasicController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {

        for (int i = 0; i <3; i++) {
            MyThread myThread = new MyThread(name + "thread" + i);
            myThread.start();
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8081";
        String api = url + "/hello?name=" + name;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(api, String.class);
        String responseEntityBody = responseEntity.getBody();
        System.out.println(responseEntityBody);

        return "Hello " + name + " header1";
    }
}
  1. 调用接口
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快,把我桶也提着

如果对您有帮助欢迎支持哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值