我是微服务和Spring Boot的新手。我有几个Spring Cloud微服务,在端口8080上运行Zuul网关。
browser | | gateway (:8080) / \ / \ / \ resource UI (:8090)
端口8090上有一个UI微服务,它有一个带有方法的控制器,返回index.html。
我为UI配置了这样的Zuul路由(我也使用Eureka):
zuul:
routes:
ui:
path: /ui/**
serviceId: myproject.service.ui
stripPrefix: false
sensitiveHeaders:
如果我致电http://localhost:8080/ui/
,一切正常,我会看到我的index.html的渲染。
是否可以通过某种方式配置Spring Cloud以使以下流程正常工作:调用http://localhost:8080/
将我们重定向到UI微服务的控制器,后者返回index.html?
所以我的想法是从我的网站的根目录打开UI。
提前致谢!
答案 0 :(得分:1)
最后,我让我的代码工作了!感谢@pan提及Zuul Routing on Root Path问题,感谢@RzvRazvan揭示了Zuul路由的工作原理。
我刚刚将控制器添加到Zuul路由的网关微服务中,其中一个端点从根http://localhost:8080/
重定向到http://localhost:8080/ui/
:
@Controller
public class GateController {
@GetMapping(value = "/")
public String redirect() {
return "forward:/ui/";
}
}
Zuul 属性,用于将端口 8080 上的网关微服务重定向为http://localhost:8080/ui/
到 UI微服务 ,作为{strong> 8090 端口上的单独Spring Boot应用程序实现为http://localhost:8090/ui/
:
zuul:
routes:
ui:
path: /ui/**
serviceId: myproject.service.ui
stripPrefix: false
sensitiveHeaders:
UI微服务的属性:
server:
port: 8090
servlet:
contextPath: /ui
最后,此调用http://localhost:8080/
将我们重定向到UI微服务的控制器,该控制器返回视图index.html
:
@Controller
public class UiController {
@GetMapping(value = "/")
public String index() {
return "index.html";
}
}
实际上,我在这种架构中渲染静态内容时遇到了另一个问题,但它与我使用Vue.js框架开发的前端配置有关。我将用几句话来描述它,以防它可能对某人有帮助。
我有以下UI微服务的文件夹结构:
myproject.service.ui
└───src/main/resources
└───public
|───static
| ├───css
| └───js
└───index.html
public
文件夹的所有内容均由 webpack 和 vue.js 中的npm run build
任务生成。我第一次打电话给http://localhost:8080/
我为index.html
200 OK ,为所有其他静态资源打了 404 ,因为它们被调用如下:
http:\\localhost:8080\static\js\some.js
因此在webpack中为静态资产配置了错误的公共路径。我在config\index.js
中更改了它:
module.exports = {
...
build: {
...
assetsPublicPath: '/ui/',
...
}
...
}
静态资产变得恰到好处。 e.g:
http:\\localhost:8080\ui\static\js\some.js
答案 1 :(得分:0)
如果您想在Zuul上使用UI(前端),可以在 resources / static 文件夹(html,css和js文件)中添加静态内容。通过这种方式,您的代理可以呈现index.html(当然,您必须在静态文件夹中拥有index.html)。通过http://localhost:8080
这种方式,代理将呈现index.html;您也可以使用其他路径,但所有这些路径都由index.html管理)
关于路由,Zuul只重定向http请求。 http://localhost:8080/ui/ 的。在8080
上运行代理(Zuul)但是/ui
是资源服务器的上下文路径。当您在此路径上进行呼叫 http://localhost:8080/ui/ 时,代理将重定向到资源服务器并实际向 http://localhost:8090/ui/发送请求
浏览器路径和http请求路径之间存在差异。浏览器路径由index.html管理,http请求由Zuul管理。我不知道我是否足够明确。
还有一件事......您可以在http请求和index.html上使用相同的路径(/ui
),当您的浏览器访问 http://localhost:8080/ui/ 时。带有http请求方法的js文件将向 http://localhost:8080/ui/ 发出http请求,然后将重定向到 http://localhost:8090/ui/ ,来自资源服务器的响应将在 http://localhost:8080/ui/ 的页面上呈现。