第一步:创建maven工程,引入需要的依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

第二步:创建controller

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhr_java@163.com
 * @date 2022/3/29 20:50
 */
@RestController
@RequestMapping("/person")
public class PersonController {

  @GetMapping("get_person")
  public String getPerson(Integer numbers) {
    String ip = getIp();
    System.out.println("请求的ip是:"+ip);
    return ip;
  }

  //获取请求对象
  public static HttpServletRequest getRequest() {
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
      return null;
    } else {
      return requestAttributes.getRequest();
    }
  }

  //获取请求的ip地址
  public static String getIp() {
    HttpServletRequest request = getRequest();
    if (request == null) {
      return "127.0.0.1";
    } else {
      return request.getRemoteHost();
    }
  }
}

第三步:启动项目,并在浏览器访问该接口
在这里插入图片描述
在这里插入图片描述
第四步:做成切面,可以对每个接口的请求次数做出统计
第五步:打包上传到服务器测试

关注我的公众号SpaceObj 领取idea系列激活码

posted on 2023-05-10 18:10  张伯灵  阅读(982)  评论(0)    收藏  举报