实现服务注册与发现
本章使用springboot2.02, java1.8
1.eureka server
添加所需依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2.配置server
server:
port: 8081
spring:
application:
name: eureka-service
#eureka.client.register-with-eureka :表示是否将自己注册到Eureka Server,默认为true。
#eureka.client.fetch-registry :表示是否从Eureka Server获取注册信息,默认为true。
#eureka.client.serviceUrl.defaultZone :设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://localhost:8081/eureka ;多个地址可使用 , 分隔
eureka:
server:
enable-self-preservation: false
instance:
prefer-ip-address: true
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.prefer-ip-address}:${server.port}/eureka/
3.集成security
#启用身份认证
security.basic.enabled=true
security.user.name=admin
security.user.password=admin
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
4.添加注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(EurekaServiceApplication.class);
springApplication.addListeners(new ApplicationPidFileWriter());
springApplication.run(args);
}
}
5.eureka client使用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class CloudClientApplication {
public static void main(String[] args) {
SpringApplication.run(CloudClientApplication.class, args);
}
@Value("${server.port}")
String port;
@RequestMapping("/test")
public String home(@RequestParam String name) {
return "hi "+name+",i am from port:" +port;
}
}
注解配置client
server:
port: 8080
spring:
application:
name: service-client
eureka:
client:
service-url:
defaultZone: http://132.232.110.87:8081/eureka/
6.访问地址
http://localhost:8081/eureka/