结合前面的服务调用
1.创建子模块eureka-server
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.创建启动器,启用eureka服务
@EnableEurekaServer
@SpringBootApplication
public class EurekaServer {
public static void main(String[] args) {
SpringApplication.run(EurekaServer.class);
}
}
3.创建application.yml配置文件,修改端口,自己注册自己,给服务取名字
server:
port: 10086
spring:
application:
name: eureka-server
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
提供方
1.在user-server中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.在user-server的启动器上添加注解 @EnableDiscoveryClient
@EnableDiscoveryClient
@SpringBootApplication
@MapperScan("cn.itcast.user.mapper")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
3.添加配置application.yml 添加服务地址和名字
server:
port: 8081
spring:
application:
name: user-server
datasource:
url: jdbc:mysql://localhost:3306/yun6
username: root
password: root
mybatis:
type-aliase-package: cn.itcast.user.pojo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
调用方
1.添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.在consumer-demo的启动器上添加注解 @EnableDiscoveryClient
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}
3.添加配置application.yml 添加服务地址和名字
server:
port: 8088
spring:
application:
name: consumer-server
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
4.修改控制器中代码
@RestController
@RequestMapping("consumer")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("{id}")
public User queryById(@PathVariable("id")Long id){
List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
ServiceInstance instance = instances.get(0);
String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
User user = restTemplate.getForObject(url,User.class);
return user;
}
}
5.eureka 不注册本身的方法
server:
port: 10087
spring:
application:
name: eureka-server
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
register-with-eureka: false