话不多说,上来就干
新建demo项目
既然本地启动了网关,自然需要试用一下看看,我们本地新建一个简易项目,模拟业务系统,测试网关的转发功能,这里我使用最简单的SpringBoot助手插件,秒秒钟新建一个SpringBoot项目,项目名称:test-http-project,项目结构下图,我们看到这个项目能正常启动。
修改一下SpringBoot项目的配置文件,修改application.properties为application.yml,个人比较喜欢yml格式,这两种格式配置文件没有好坏之分,能办事就行。
配置文件配置最简单的一些参数,修改端口号为8081,(如果不配置,默认端口号为8080),再重新启动一下,检查配置是否生效。
启动后端口号以为修改为8081,说明配置文件已经生效。
引入soul相关配置及注解
想使用网关,必然需要在业务系统项目中配置网关的信息,soul网关也不例外,如何配置,官方文档最权威,我们先去官网看一下soul官方文档
在官方文档:soul->用户使用文档->http用户我们找到我们想要的东西
引入依赖
那我们就引入这些jar包
<dependency>
<groupId>org.dromara</groupId>
<artifactId>soul-spring-boot-starter-client-springmvc</artifactId>
<version>${last.version}</version>
</dependency>
但是好像直接通过maven拉取阿里的jar包仓库失败
突然想起来,之前我本地拉下的soul项目,只是compile了一下,编译通过而已,并没有通过install命令
所以现在将soul项目的各个模块打包到本地仓库,在soul项目根路径下,执行
mvn install
命令
我们自己的demo项目中的依赖soul的jar包的版本号也修改为我们打的soul对应模块包的版本号:2.2.1
修改配置文件
那我们就在自己的demo项目中配置
#soul配置项
soul:
http:
adminUrl: http://localhost:9095
port: 8081
contextPath: /http
appName: sys
full: false
# adminUrl: 为你启动的soul-admin 项目的ip + 端口,注意要加http://
# port: 你本项目的启动端口
# contextPath: 为你的这个mvc项目在soul网关的路由前缀,这个你应该懂意思把? 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由.
# appName:你的应用名称,不配置的话,会默认取 `spring.application.name` 的值
# full: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller
修改demo项目的yml配置文件
这里有个坑,就是soul.http.contextPath这一项一旦配置例如 /api、/http、/order这种url前缀,server.servlet.context-path这一项最好就不要配置,否则soul网关路由不到具体的url方法,应该是soul源码中默认读取的配置项soul下的contextPath,然后拼接上controller层的路径,并没有读取spring的tomcat路径配置,现在只是猜想,等我读读源码再回来闭环
新增具体业务代码
新建vo包->新建UserVO类
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class UserVO {
private Integer id;
private String username;
private Integer gender;
}
新建controller包->新建UserController->新建查找用户方法
注意:千万要在controller类名和具体方法名上都加上注解 @SoulSpringMvcClient ,其中path属性为对应的请求路径
import com.csc.soul.http.vo.UserVO;
import org.dromara.soul.client.springmvc.annotation.SoulSpringMvcClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
@SoulSpringMvcClient(path = "/user")
public class UserController {
@GetMapping("/find/{id}")
@SoulSpringMvcClient(path = "/find/{id}")
public UserVO findById(@PathVariable("id") Integer id) {
return new UserVO().setGender(0).setId(id).setUsername("豆浆油条蓝胖子");
}
}
测试
demo项目配置的端口为8081
postman请求地址 localhost:8081/http/user/find?id=1
响应
{
"id": 1,
"username": "豆浆油条蓝胖子",
"gender": 0
}
测试
启动服务
启动soul网关管理后台
启动soul网关
启动soul网关
端口配置
port: 9195
启动demo项目
打开网关管理后台
打开网关管理后台,打开左侧的pluginList菜单-divide,右侧展示了代理网关地址信息
我们打开modify(修改)
由页面配置信息我们可以看到,我们自己项目的ip:port都已经注册到了soul网关上了
网关测试
使用postman,请求路径 localhost:9195/http/user/find?id=1
响应
{
"id": 1,
"username": "豆浆油条蓝胖子",
"gender": 0
}
可以看到,网关起了作用,本来我们项目端口是8081,现在通过9195这个网关端口,路由到8081服务
这就是今天的内容,下一期从零开始soul网关,请稍等。。。