1.搭建Eureka Server
1.1创建工程,导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
1.2配置application.yml
server:
port: 9000
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname} : ${server.port} /eureka/
1.3 配置启动类
@SpringBootApplication
@EnableEurekaServer //激活Eureka Server
public class EurekaServerApplication {
public static void main( String[ ] args) {
SpringApplication.run( EurekaServerApplication.class, args) ;
}
}
2.将服务提供者注册到Eureka Server上
2.1 引入Eureka Client坐标
< ! -- 引入Eureka Client依赖-- >
< dependency>
< groupId> org. springframework. cloud< / groupId>
< artifactId> spring- cloud- starter- netflix- eureka- client< / artifactId>
< / dependency>
2.2 修改application.yml添加EurekaServer的信息
#配置Eureka
eureka:
client:
service- url:
defaultZone: http: / / localhost: 9000 / eureka/
instance:
prefer- ip- address: true #使用ip地址注册
2.3 修改启动类,添加服务发现的支持(可选)
* /
@SpringBootApplication
@EntityScan ( "com.bjpowernode.product.entity" )
@EnableEurekaClient
public class ProductApplication {
public static void main ( String[ ] args) {
SpringApplication. run ( ProductApplication. class , args) ;
}
}
3.服务消费者通过注册中心获取服务列表,并调用
3.1 引入Eureka Client依赖
< ! -- 引入Eureka Client依赖-- >
< dependency>
< groupId> org. springframework. cloud< / groupId>
< artifactId> spring- cloud- starter- netflix- eureka- client< / artifactId>
< / dependency>
3,2 配置application.yml文件
#配置Eureka
eureka:
client:
service- url:
defaultZone: http: / / localhost: 9000 / eureka/ #多个eurekaserver之间用, 隔开
instance:
prefer- ip- address: true #使用ip地址注册
3.3 修改启动类,添加服务发现的支持(可选)
注意:需要在服务消费者方的启动类中,创建RestTemplate对象,并交给spring容器管理
@SpringBootApplication
@EntityScan ( "com.bjpowernode.eureka.entity" )
@EnableDiscoveryClient
public class OrderApplication {
@Bean
public RestTemplate restTemplate ( ) {
return new RestTemplate ( ) ;
}
public static void main ( String[ ] args) {
SpringApplication. run ( OrderApplication. class , args) ;
}
}
3.4 在服务调用者中的Controller层,注入DiscoveryClient
private DiscoveryClient discoveryClient;
3.5 调用discoveryClient方法
@Controller
@RequestMapping ( "/order" )
public class OrderController {
@Autowired
private RestTemplate restTemplate;
private DiscoveryClient discoveryClient;
@RequestMapping ( "/buy/{id}" )
@ResponseBody
public Product findById ( @PathVariable Long id) {
List< ServiceInstance> instances = discoveryClient. getInstances ( "service-product" ) ;
ServiceInstance instance = instances. get ( 0 ) ;
String host = instance. getHost ( ) ;
int port = instance. getPort ( ) ;
Product product = restTemplate. getForObject ( "http://" + host+ ":" + port+ "/product/" + id, Product. class ) ;
return product;
}
}
搞定!!!!!!!