服务提供与消费(上篇)
2020/2/27 17:15:59
本文主要是介绍服务提供与消费(上篇),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
上一篇主要介绍服务注册中心,对常见几种注册中心进行了对比,主要介绍了Eureka的架构,并搭建了一个最简单的注册中心,本文将主要介绍注册中心的使用,上篇主要介绍服务提供者,下篇介绍服务消费者
服务提供者 - provider
假设有一个电商交易系统,其中user-service为用户基础服务,供前端展示系统mall-admin调用
user-service 只提供一个简易的查询服务,根据输入的用户名(userName)和年龄(age)返回用户信息
项目实战
代码及配置
pom.xml 增加依赖
<parent> <artifactId>spring-cloud</artifactId> <groupId>com.kk</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <artifactId>user-service</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> 复制代码
parent pom.xml
parent pom同上篇,详情可直接参考github中代码
启动类 UserServiceApplication 增加注解
@SpringBootApplication @EnableDiscoveryClient public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } } 复制代码
user-service 接口类
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserServiceImpl userService; @RequestMapping("/info") public String UserInfoAction(@RequestParam String userName, @RequestParam Integer age) { return userService.getUserInfo(userName, age); } } 复制代码
配置文件 application.yml 增加配置
server: port: 8091 spring: application: name: user-service # 在注册中心中显示和调用的名称 eureka: client: service-url: defaultZone: http://localhost:8090/eureka/ # 将自己注册到该地址的Eureka上面去 复制代码
测试
服务提供者已开发、配置完成,可以进行简要测试 依次启动eureka-server和user-service两个服务
启动界面
增加@EnableDiscoveryClient注解后,项目就具备了服务注册功能,启动工程后,就会向注册中心(eureka-server)注册,同时在注册中心界面也可以看到USER-SERVICE了,如图所示
测试验证
在浏览器或postman等工具输入 http://localhost:8091/user/info?userName=abcd&age=12 可以查看到“username abcd and age is 12”
示例代码
相关文章
这篇关于服务提供与消费(上篇)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南
- 2024-09-30Dnd-Kit学习:新手快速入门指南