创建Eurake Server
1、选中项目右击–>New–>Module
勾选Web->Spring Web
勾选Spring Cloud Discovery->Eureka Server
2、修改application.properties文件
server.port=8761
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
3、修改启动类DemocloudApplication
添加@EnableEurekaServer,该注解表明标注类是一个Eureka Server。
@SpringBootApplication
@EnableEurekaServer
public class DemocloudApplication {
public static void main(String[] args) {
SpringApplication.run(DemocloudApplication.class, args);
}
}
4、启动项目
在浏览器中输入http://localhost:8761/
1、勾选Spring Cloud Discovery->Eureka Discovery Client
2、修改application.properties文件
server.port=7901
spring.application.name=demo-user
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
logging.level.root=INFO
3、修改启动类DemoclientApplication
添加@EnableEurekaClient,该注解表明标注类是一个生产者。
@SpringBootApplication
@EnableEurekaClient
public class DemoclientApplication {
public static void main(String[] args) {
SpringApplication.run(DemoclientApplication.class, args);
}
}
4、创建Controller
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/sayHello")
public String sayhello(){
return "I`m provider 1 ,Hello consumer!";
}
}
5、运行服务
在浏览器中输入http://localhost:7901/user/sayHello
创建消费者1、勾选Spring Cloud Discovery->Eureka Discovery Client
2、修改application.properties文件
server.port=7902
spring.application.name=demo-guest
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
logging.level.root=INFO
3、修改启动类DemoguestApplication
添加@EnableDiscoveryClient,该注解表明标注类是一个消费者。
@SpringBootApplication
@EnableDiscoveryClient
public class DemoguestApplication {
public static void main(String[] args) {
SpringApplication.run(DemoguestApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
4、创建Controller
@RestController
public class GuestController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/hello")
public String hello(){
//服务地址 http://{服务提供者应用名名称}/{具体的controller}
String url="http://DEMO-USER/user/sayHello";
//返回值类型和我们的业务返回值一致
return restTemplate.getForObject(url, String.class);
}
}
5、运行服务
在浏览器中输入http://localhost:7902/hello