上一篇主要介绍服务注册中心,对常见几种注册中心进行了对比,主要介绍了Eureka的架构,并搭建了一个最简单的注册中心,本文将主要介绍注册中心的使用,上篇主要介绍服务提供者,下篇介绍服务消费者
假设有一个电商交易系统,其中user-service为用户基础服务,供前端展示系统mall-admin调用
user-service 只提供一个简易的查询服务,根据输入的用户名(userName)和年龄(age)返回用户信息
<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同上篇,详情可直接参考github中代码
@SpringBootApplication @EnableDiscoveryClient public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } } 复制代码
@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); } } 复制代码
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”