企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## Eureka服务端 服务端引入依赖: ~~~ <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>2.0.1.RELEASE</version> </dependency> </dependencies> ~~~ 启动类加注解: ~~~ package com.like; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer //标注此为eureka服务端 public class EurekaServer { public static void main(String[] args) { SpringApplication.run(EurekaServer.class); } } ~~~ ~~~ server: port: 10086 //端口 spring: application: name: eureka-server //指定当前服务名 eureka: client: service-url: defaultZone: http://localhost:10086/eureka //服务注册的地址,将当前服务注册到eureka中.这里是将自己注册要自己.必须要带 /eureka instance: prefer-ip-address: true //设置eureka服务的IP地址 ip-address: 127.0.0.1 //设置为本机,如果不设置,默认就为本机IP ~~~ 打开 [http://localhost:10086/](http://localhost:10086/) 可以看到服务. ## 用户服务客户端 导入依赖: ~~~ <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.0.1.RELEASE</version> </dependency> ~~~ 启动类: ~~~ package com.like; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan("com.like.mapper") @EnableDiscoveryClient //因为spring-cloud 里面有多个注册中心,所以这里使用EnableDiscoveryClient注解,而不是EnableEurekaClient public class UserServer { public static void main(String[] args) { SpringApplication.run(UserServer.class); } } ~~~ 配置: ~~~ server: port: 8081 //端口 spring: application: name: user-server //当前服务ID datasource: url: jdbc:mysql://192.168.10.10:3306/jdbc username: homestead password: secret eureka: client: service-url: defaultZone: http://localhost:10086/eureka/ //注册中心的地址 mybatis: type-aliases-package: com.like.pojo //pojo别名 ~~~ ## 调用服务客户端 配置文件: ~~~ server: port: 8082 spring: application: name: consumer-server eureka: client: service-url: defaultZone: http://localhost:10086/eureka/ ~~~ 启动类: ~~~ package com.like; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDiscoveryClient public class ConsumerServer { public static void main(String[] args) { SpringApplication.run(ConsumerServer.class); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ~~~