springboot整合(分布式)

tech2026-10-02  2

首先创建一个空工程,然后用springboot初始化器创建三个模块:服务注册中心,服务提供者,服务消费者 首先看注册中心:

1、配置Eureka信息 application.yml文件配置: server: port: 8761 eureka: instance: hostname: eureka-server # eureka实例的主机名 client: register-with-eureka: false #不把自己注册到eureka上 fetch-registry: false #不从eureka上来获取服务的注册信息 service-url: defaultZone: http://localhost:8761/eureka/ 2、开启注册中心功能@EnableEurekaServer @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }

服务提供者 application.yml文件配置:

server: port: 8002 spring: application: name: provider-ticket eureka: instance: prefer-ip-address: true #注册服务的时候用服务的IP地址 client: service-url: defaultZone: http://localhost:8761/eureka/

service层:

@Service public class TicketService { public String getTicket(){ System.out.println("8001"); return "樱空桃の绝对领域"; } }

controller层:

@RestController public class TicketController { @Autowired TicketService ticketService; @GetMapping("/ticket") public String getTicket(){ return ticketService.getTicket(); } }

服务消费者 application.yml文件配置:

spring: application: name: consumer-user server: port: 8200 eureka: #注册中心 instance: prefer-ip-address: true #注册服务的时候用服务的IP地址 client: service-url: defaultZone: http://localhost:8761/eureka/

controller层:

@RestController public class UserController { @Autowired RestTemplate restTemplate; @GetMapping("/buy") public String buyTicket(String name){ String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class); return name+"购买了"+s; } }
最新回复(0)