下午有时间,继续接着,上次的看。web
上次已经完成了Eureka的搭建,和集群,今天开始研究服务的注册和发布spring
建立一个工程,为注册服务,向Eureka服务中心,进行注册app
选择好之后,建立成功注册服务工程ide
开始进行配置测试
application.properties配置文件 里面,增长服务配置idea
spring.application.name=spring-cloud-consumer server.port=9000 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
spring.application.name 服务名称,用户服务之间,进行调用3d
port端口 eureka.client.serviceUrl.defaultZone设置与Eureka Server交互的地址,查询服务和注册服务都须要依赖这个地址。多个地址可以使用 , 分隔。server
Springboot的启动文件增长配置注解,让Eureka发现此服务,进行注册blog
@EnableDiscoveryClient//启用服务注册与发现
启动项目,访问Eureka8000端口,发现,新增了一个服务,服务名,与配置文件相同接口
建立controller
package com.example.democloudserver.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { /** * 测试服务注册 * @param name * @return */ @GetMapping("/hello") public String index(@RequestParam String name){ return "hello-2:"+ name; } }
好了,这一步,已经说明,服务注册成功,下面,建立调用服务,用过Eureka调用,刚才注册的服务
建立调用服务和以前基本相同,idea建立工程,就能够,惟一不一样的是,调用服务,须要Feign,全部,在这里,还要进行勾选这个
建立成功项目,开始配置
spring.application.name=spring-cloud-consumer server.port=9001 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
启动项配置
@EnableDiscoveryClient//启用服务注册与发现 @EnableFeignClients//启用feign进行远程调用
开启feign的做用,是进行远程调用,开启EnableDiscoveryClient,是为了让Eureka发现
建立一个接口,经过注解,远程调用刚才的注册服务
package com.example.servicefeign.interfaceServer; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name= "spring-cloud-producer") //name:远程服务名,及spring.application.name配置的名称 public interface HelloRemote { @RequestMapping(value = "/hello") public String hello(@RequestParam(value = "name") String name); }
定义好了之后,能够注入controller,进行调用
package com.example.servicefeign.controller; import com.example.servicefeign.interfaceServer.HelloRemote; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired HelloRemote hello;//注册接口层 @RequestMapping("/hello/{name}") public String index(@PathVariable("name") String name) { return hello.hello(name); } }
启动服务调用层,访问controller进行访问,调动注册的服务,成功
这里,我也顺便测试了,服务中心提供的服务均衡负载
注册服务,设置不一样的端口,相同的服务名,进行启动,修改输出controller输出为
"hello-2:"+ name
"hello-1:"+ name
页面屡次请求,发现两种结果交替出现。