# 如何通过互联网访问本地Spring Boot程序

当你需要别人远程访问你本地的Spring Boot的程序的时候，你可以通过Ngrok来帮助你来实现。

## 什么是Ngrok
Ngrok可以创建一个http隧道，并为您提供一个公共URL，重定向到本地机器上的指定端口。它是一个很棒的开发或者测试目的使用的工具。

Ngrok的官网地址是：[https://ngrok.com](https://ngrok.com) 。

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235327094/7fYvdt4eu.png align="left")

## Ngrok Spring Boot Starter
Spring Boot的Web端口可以通过**Ngrok Spring Boot Starter**暴露到互联网。

**Ngrok Spring Boot Starter**将会根据你的操作系统自动下载Ngrok的二进制文件并缓存到`home_directory/.ngrok2` 目录。

每次运行Spring Boot程序的时候，Ngrok会自动构建指向Spring Boot Web程序的http隧道。

该Starter的地址为：[https://github.com/kilmajster/ngrok-spring-boot-starter](https://github.com/kilmajster/ngrok-spring-boot-starter)

## 注册Ngrok
- 注册Ngrok
访问Ngrok官网：https://ngrok.com/，注册Ngrok账号

- 获取Ngrok的认证码
访问：
https://dashboard.ngrok.com/get-started/your-authtoken ，即可看到authtoken。

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235396168/x-9Z1SSId.png align="left")

## Spring Boot 代码演示

- 新建演示项目


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235424763/PENGixIqC.png align="left")

- 简单的演示代码

```java
@SpringBootApplication
@RestController
public class NgrokDemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(NgrokDemoApplication.class, args);
   }

   @GetMapping("/")
   public String index(){
      return "Hello Ngrok!";
   }

}
```

- 添加ngrok-spring-boot-starter依赖

Gradle:

```groovy
implementation 'io.github.kilmajster:ngrok-spring-boot-starter:0.6.0'
```

或Maven：

```xml
<dependency>
  <groupId>io.github.kilmajster</groupId>
  <artifactId>ngrok-spring-boot-starter</artifactId>
  <version>0.6.0</version>
</dependency>
```

- 简单配置
在application.yaml 中:

```yaml
ngrok:
  enabled: true # 开启ngrok
  auth-token:  ------# 复制上面获取的authtoken到此处
```
- 启动程序

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235558143/BogwBy0V8.png align="left")


通过Spring Boot控制台，你可以发现：

1. 启动时程序自动会自动下载ngrok并解压缓存到系统用户的.ngrok下。
2. 启动ngrok，ngrok dashboard的地址是：http://127.0.0.1:4040


- 访问ngrok dashboard


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235606232/I4Tes90pJ.png align="left")

你会发现ngrok为我们提供了两个公网访问的地址，分别是http和https的。

- 访问ngrok提供的公网地址

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235622342/wJwfG4X1D.png align="left")


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235629313/7MHIbfR-U.png align="left")

用手机访问：

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235638955/RRRldv5A2.png align="left")

ping 域名返回的也是公网的ip：


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666235651583/HUizeP4bv.png align="left")

更多关于如何使用的，请参考Starter的项目地址。

感谢支持我的书：《从企业级开发到云原生微服务:Spring Boot实战》

头条文章地址：[https://www.toutiao.com/article/7080505822463214093/](https://www.toutiao.com/article/7080505822463214093/)

参考资料：
https://github.com/kilmajster/ngrok-spring-boot-starter


