1.首先新建一个空的项目:new -> project -> empty project
2.创建Server
-
new module -> Spring Initializr -> Cloud Discovery -> Eureka Server
application.yml
server:
port: 8761
eureka:
instance:
hostname: eureka-server #eureka实例的主机名
client:
register-with-eureka: false #不把自己注册到eureka上
fetch-registry: false #不从eureka上来获取服务的注册信息
service-url:
defaultZone: http://localhost:8761/eureka/
ServerApplication
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
此时启动该项目,访问http://localhost:8761/会出现如下界面:
3.创建PROVIDER-TICKER
-
new module -> Spring Initializr -> Cloud Discovery -> Eureka Discovery
application.yml
server:
port: 8002
spring:
application:
name: provider-ticker
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Service
@Service
public class TickerService {
public String getTicker(){
return "one ticker";
}
}
Controller
@RestController
public class TickerController {
@Autowired
TickerService tickerService;
@GetMapping(value = "/ticket")
public String getTicker(){
System.out.println("8001");
return tickerService.getTicker();
}
}
4.创建CONSUMER-USER
-
new module -> Spring Initializr -> Cloud Discovery -> Eureka Discovery
application.yml
spring:
application:
name: consumer-user
server:
port: 8200
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Application
@EnableDiscoveryClient //开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerUserApplication.class, args);
}
@LoadBalanced //使用负载均衡机制
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Controller
@RestController
public class UserController {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/buy")
public String buyTicker(String name){
String s=restTemplate.getForObject("http://PROVIDER-TICKER/ticket",String.class);
return name+"购买了"+s;
}
}