构建一个Eureka服务器,两个服务。两个服务都注册到Eureka服务器中。服务一提供的服务是:接收一个参数并返回给用户。服务二:调用服务一中的服务。

构建过程
1.创建普通maven项目(springcloud-01-test)

2.选择项目鼠标右键新增模块(springcloud-server)
(角色:Eureka服务器)


填写好GroupId(项目的目录结构),ArtifactId(项目名)

该模块作为Eureka服务器。需要的依赖有Spring Web模块以及Eureka server

Eureka服务器代码
①启动类中添加一个@EnableEurekaServer注解
@SpringBootApplication @EnableEurekaServer public class SpringcloudServerApplication { public static void main(String[] args) { SpringApplication.run(SpringcloudServerApplication.class, args); } } 复制代码
②配置application.properties配置文件,配置如下。
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
复制代码
启动该模块。打开浏览器输入http://localhost:8761

如图所示,启动成功。但是目前没有发现任何的服务。
3.选择项目鼠标右键新增模块(springcloud-provider)
(角色:服务一:接收一个参数并返回给用户)
新增模块步骤与第2步类似,但是依赖选择Spring Web和Eureka Discovery Client

服务一代码
①在启动类中添加一个@EnableEurekaClient注解
@SpringBootApplication @EnableEurekaClient public class SpringcloudProviderApplication { public static void main(String[] args) { SpringApplication.run(SpringcloudProviderApplication.class, args); } } 复制代码
②在与启动类统一目录下新建一个ProviderController.java控制器类,代码如下。
@RestController public class ProviderController { @RequestMapping(value = "/person/{name}",method = RequestMethod.GET) public String findName(@PathVariable("name") String name){ return name; } } 复制代码
③配置application.properties配置文件,配置如下。
spring.application.name=service-provider eureka.instance.hostname=localhost eureka.client.service-url.defaultZone=http://localhost:8761/eureka 复制代码
启动该模块,刷新一下浏览器。

服务一注册成功!!
4.选择项目鼠标右键新增模块(springcloud-invoker)
(角色:服务二:调用服务一中的方法)
新建模块步骤和依赖与第3步一样。
服务二代码
①在启动类中添加一个@EnableDiscoveryClient注解
@SpringBootApplication @EnableDiscoveryClient public class SpringcloudInvokerApplication { public static void main(String[] args) { SpringApplication.run(SpringcloudInvokerApplication.class, args); } } 复制代码
②在与启动类统一目录下新建一个InvokerController.java控制器类,代码如下。
@RestController @Configuration public class InvokerController { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } @RequestMapping(value = "/router",method = RequestMethod.GET) public String router(){ RestTemplate restTemplate = getRestTemplate(); String name = restTemplate.getForObject("http://service-provider/person/chonor",String.class); return name; } } 复制代码
③配置application.properties配置文件,配置如下。
server.port=9000 spring.application.name=service-invoker eureka.instance.hostname=localhost eureka.client.service-url.defaultZone=http://localhost:8761/eureka 复制代码
启动该模块,刷新一下浏览器。

服务一,服务二均注册成功!!
原文
https://juejin.im/post/5e76dd496fb9a07cb83e477c
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 使用IDEA搭建第一个Spring Cloud项目(图解)