1.搭建Eureka的注册中心
Eureka服务中心 application.yaml文件的配置
#配置自己的端口号
server:
port: 10086
#配置注册中心让自己也能注册到自己 Client就不会因为注册不到自己而报错了
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
# 指定status是自己指定的ip地址 而不是自己的主机名
instance:
instance-id: ${spring.application.name}:${server.port}:@project.version@
prefer-ip-address: true
ip-address: 127.0.0.1
#配置自己的服务名
spring:
application:
name: eureka-service
服务提供者的application.yaml的配置
server:
port: 9090
#配置别名
mybatis:
type-aliases-package: com.hdh.pojo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
instance-id: ${spring.application.name}:${server.port}:@project.version@
prefer-ip-address: true
ip-address: 127.0.0.1
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/shop
username: root
password: 12345
application:
name: user-service
服务调用者的application.yaml的配置
#配置自己的端口号
server:
port: 10086
#配置注册中心让自己也能注册到自己 Client就不会因为注册不到自己而报错了
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
# 指定status是自己指定的ip地址 而不是自己的主机名
instance:
instance-id: ${spring.application.name}:${server.port}:@project.version@
prefer-ip-address: true
ip-address: 127.0.0.1
#配置自己的服务名
spring:
application:
name: eureka-service
调用者发起调用Cousmer 也就是Controller
application.class起步类
//拉取在注册中心注册过的服务
@EnableDiscoveryClient
@SpringBootApplication
public class ApplicationService {
@Bean
//对json数据自动处理
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ApplicationService.class);
}
}
获取指定服务 通过discoveryClient.getInstances("user-service");
@RestController
@RequestMapping("User")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("{id}")
public User selectById(@PathVariable(name = "id") Integer id) {
//获取注册过的服务 通过name获取实例
List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
ServiceInstance insrance = instances.get(0);
//获取ip和端口
String host = insrance.getHost();
int port = insrance.getPort();
String url = "http://"+host+":"+port+"/User/" + id;
User user = restTemplate.getForObject(url, User.class);
return user;
}
}
被调用者也就是Service
//推送自己的服务 @EnableEurekaServer @SpringBootApplication public class EurekaService { public static void main(String[] args) { SpringApplication.run(EurekaService.class); } }
Eureka客户端和服务端的起步坐标
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<!-- Eureka服务端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>