Eureka主要分为服务端与客户端
- 服务端需要加上两个注释
@EnableEurekaServer
@SpringBootApplication
,服务端注重配置 - 客户端要加上两个注释
@EnableDiscoveryClient
@SpringBootApplication
,基本上在一个分布式系统中,只要会提供服务的组件,就一定要注册到服务注册与发现组件中(Eureka,Zookeeper, Consul)都要加上@EnableDiscoveryClient
这个注释
Eureka 服务端
服务端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
服务端最简配置
spring.application.name=eureka-server
server.port=8761
eureka.instance.hostname=localhost
# 由于该应用为注册中心,所以设置为 false , 代表不向汪册中心注册自己
eureka.client.registerwith-eureka=false
# 由于注册中心的职责就是维护服务实例他并不需要去检索服务,所以也设置为 false
eureka.client.fetch-registry=false
Eureka服务端部署到tomcat,War包方式
第一步:改造主类,继承SpringBootServletInitializer并覆盖configure方法
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(EurekaServerApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class);
}
}
第二步,修改打包方式,添加maven打包插件,指定打出来的war包名称为ROOT(这样就可以通过IP+Port直接访问Eureka服务端了)
<packaging>war</packaging>
<build>
<finalName>ROOT</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</build>
Eureka提供服务的客户端
服务注册客户端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
服务注册客户端配置
server:
port: 8081
spring:
application:
name: service-provider
eureka:
client:
serviceUrl:
defaultZone: http://192.168.236.128:8080/eureka/
注册服务的类
跟spring boot提供rest的类一样的写法
Eureka消费服务的客户端
发现服务的客户端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
发现服务的客户端配置
server:
port: 8081
spring:
application:
name: service-consumer
eureka:
client:
serviceUrl:
defaultZone: http://192.168.236.128:8080/eureka/
发现并调用服务的类
第一步,先使用feign映射服务提供者的服务
@FeignClient("service-provider")
public interface OrderClient {
@RequestMapping("/create")
public String create();
@RequestMapping("/cancel")
public String cancel();
@RequestMapping("/query")
public String query();
}
第二步,再在服务调用者这边暴露一个rest供前端调用
@RestController
public class EurekaConsumer {
@Autowired
private OrderClient orderClient;
@RequestMapping("/createOrder")
public String createOrder(){
System.out.println("creating order!");
return orderClient.create();
}
@RequestMapping("/cancelOrder")
public String cancelOrder(){
System.out.println("cancelling order!");
return orderClient.cancel();
}
@RequestMapping("/queryOrder")
public String queryOrder(){
System.out.println("querying order!");
return orderClient.query();
}
}
来源:CSDN
作者:JB324
链接:https://blog.csdn.net/JB324/article/details/103781289