记录一下用spring cloud Eureka搭建服务注册与发现框架的过程。
为了创建spring项目方便,使用了STS。
一.Eureka注册中心
1.新建项目-Spring Starter Project
2.选择下面两项
3.修改application.properties
server.port=8761
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
4.在*.Application.java 启动方法上加注解
@EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
5.启动,浏览器访问http://localhost:8761
二.服务注册到服务中心
新建项目(步骤同一的1,2步)
3.修改application.properties
spring.application.name=add-service server.port=8762 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ eureka.instance.lease-renewal-interval-in-seconds=50 eureka.instance.lease-expiration-duration-in-seconds=30
4.在pom.xml增加以下两个依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.4.RELEASE</version> </dependency>
5.在启动类上加以下注解
@EnableDiscoveryClient @SpringBootApplication @EnableFeignClients public class ServiceAddApplication { public static void main(String[] args) { SpringApplication.run(ServiceAddApplication.class, args); } }
6.新建AddController.java
@Controller public class AddController { @RequestMapping(value = "/add", method = RequestMethod.GET) @ResponseBody public int add(@PathParam("a") int a, @PathParam("b") int b) { return a + b; } }
7.启动该项目(也需要启动注册中心)
访问localhost:8761
8.访问localhost:8762/add?a=1&b=3
三.服务间调用
新建第二个服务并注册到服务中心
在第二个服务pom.xml文件中添加以下依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.4.RELEASE</version> </dependency>
创建接口
@FeignClient(name = "add-service") public interface FeignSrv { @RequestMapping(value = "/add") public int add(@RequestParam(value = "a") int a, @RequestParam(value = "b") int b); }
@RestController public class FeignAdd { @Autowired FeignSrv FeignSrv; @RequestMapping("/index") public int index(@RequestParam("a") int a, @RequestParam("b") int b) { return FeignSrv.add(a, b); } }
至此,服务注册,发现与调用就完成了。
此文章后续继续更新。