一:编写eureak服务
1.jar包依赖
web:web
Colud Dicovery:Eureka Server
2.编写application.properties
#设置端口号
server.port=8761
#主机的名字
eureka.instance.hostname=eureak-service
#不希望将自己这个工程注册到注册中心(如果考虑到eureka的高可用)
eureka.client.register-with-eureka=false
#不从eureka上获取到货物的注册信息(本身eureka服务,不是消费者)
eureka.client.fetch-registry=false
#注定注册中心
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
3.启动类中设置该项目为一个eureka服务
@SpringBootApplication
@EnableEurekaServer //将该项目表示为一个eureka服务
二:编写服务提供者
1.jar包依赖
Colud Dicovery:Eureka Discovery
2.编写application.properties
#设置启动端口号
server.port=8081
#设置注册到注册中心的应用程序名称
spring.application.name=item-service
#指定注册中心的地址
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
#注册的时候使用的服务的ip地址进行注册
eureka.instance.prefer-ip-address=true
3.编写service
@Service
public class ItemService{
public String getItemById(String id){
return "您查询的是**"+id+"**号商品";
}
}
4.编写controller
@RestController
public class controller{
@Autowired
private ItemService itemService;
@GetMapping("/item/{id}")
public String item(@PathVariable("id") String id){
return itemService.getItemById(id);
}
}
三:服务的消费者
1.依赖jar包
WEB:web
Colud Dicovery:Eureka Server
2.编写配置文件
#端口
server.port=8888
#应用名
spring.application.name=item-web
#指定注册中心的地址
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
#注册的时候也采用ip地址注册
eureka.instance.prefer-ip-address=true
3.编写启动类
@SpringBootApplication
@EnableDiscoveryClient //开启发现服务的功能
public class ItemWebApplication{
public static void main(String[] args){
SpringApplication.run(ItemWebApplication.class,args);
}
//eureka是通过发送http请求json数据来实现通讯
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
4.编写controller
@RestController
public class UserContorller {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/buy/{id}")
public String BuyItem(@PathVariable("id") String id){
//第一个表示请求的url:
//返回的数据类型String
String str = restTemplate.getForObject("http://192.168.25.1:8081/item/" + id, String.class);
return str;
}
}