就是新建一个注册中心
server:
port: 8761
eureka:
instance:
hostname: server #eureka实例的主机名
client:
register-with-eureka: false #不能把自己注册到eureka上
fetch-registry: false #不从eureka上来获取服务的注册信息
service-url:
defalutZone: http://localhost:8761/eureka/
为了方便测试,这里把注册中心打包成可运行的jar,单独运行,不占用idea
server:
port: 8001
spring:
application:
name: ticket
eureka:
instance:
prefer-ip-address: true #注册服务的时候使用服务的ip地址
client:
service-url:
defalutZone: http://localhost:8761/eureka/
package com.xiaostudy.springcloud_service.service; import org.springframework.stereotype.Service; @Service public class TicketService { public String getTicket() { return "服务提供者。。。"; } }
package com.xiaostudy.springcloud_service.web.controller; import com.xiaostudy.springcloud_service.service.TicketService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TicketController { @Autowired TicketService ticketService; @GetMapping("/ticket") public String getTicket() { return ticketService.getTicket(); } }
正常,也可以去注册中心看
同样,为了方便测试,把服务也打包成jar,单独运行,不占用idea
server:
port: 8200
spring:
application:
name: user
eureka:
instance:
prefer-ip-address: true #注册服务的时候使用服务的ip地址
client:
service-url:
defalutZone: http://localhost:8761/eureka/
//开启发现服务功能 @EnableDiscoveryClient
@LoadBalanced//使用负载均衡机制 一定要加@LoadBalanced,不让报连接超时 @Bean//帮我们发送http请求 public RestTemplate restTemplate() { return new RestTemplate(); }
package com.xiaostudy.springcloud_consumers.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class UserController { @Autowired RestTemplate restTemplate; @GetMapping("/get") public String getTicket() { String s = restTemplate.getForObject("http://TICKET/ticket", String.class); return "获取了:" + s; } }
已经启动了
注册中心上也可以看到
springboot2.1.6用以上方法也可行。
springboot2.x以上可能后面测试
springcloud【基于springboot1.x】的简单发布服务和使用
原文:https://www.cnblogs.com/xiaostudy/p/11228791.html