微服务调用方式之Ribbon的用法
导入Ribbon的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
使用注解的方式配置RestTemplate
@Configuration
public class MyConfigurer {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
在需要调用其他服务接口的地方使用@Autowired注解直接注入RestTemplate 类 在调用restTemplate.getForObject(url, Object.class)方法 url:是的接口的地址(http://product-service (这里是每个微服务在向注册中心注册的时候给自己起的名字,在配置文件中的是spring.application.name : product-service 的属性值)/a/b(这里是接口的具体地址))
package net.xdclass.order_service.service.impl;
import net.xdclass.order_service.domain.ProductOrder;
import net.xdclass.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.net.www.URLConnection;
import sun.net.www.http.HttpClient;
import java.util.Date;
import java.util.UUID;
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private RestTemplate restTemplate;
@Override
public ProductOrder save(int productId) {
Object obj = restTemplate.getForObject("http://product-service/api/find?id=2",
Object.class);
System.out.println(obj);
return null;
}
}
微服务调用方式之feign的用法
加入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在启动类上增加@EnableFeignClients注解 新增加一个接口 并类上方添加@FeignClient(name=“product-service (这里是被调用方的服务名)”) 在新增的接口中写,需要调用对应服务的,Controller层的方法。方法的参数和请求的方式、地址必须相同。 传的参数是基础类型时,每个参数前需要添加@RequestParam(“xx”) 注解,方法上添加 @GetMapping("/a/b/c") 注解。 传的参数是对象类型时,要添加@RequestBody 注解,方法上添加@PostMapping("/a/b/c") 注解
@FeignClient("product-service")
public interface ProductClient{
@PostMapping(value = "/updateProduct")
int update(@RequestBody Entity entity);
@GetMapping(value = "/deleteProduct")
int findById(@RequestParam("id") int id);
}
在需要调用其他服务接口的地方使用@Autowired注解直接注入新增的接口类,然后调用接口中对应的方法。返回的是json字符串。
package net.xdclass.order_service.service.impl;
import net.xdclass.order_service.domain.ProductOrder;
import net.xdclass.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.net.www.URLConnection;
import sun.net.www.http.HttpClient;
import java.util.Date;
import java.util.UUID;
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private ProductClient productClient;
@Override
public ProductOrder save(int productId) {
String response = productClient.findById(productId);
System.out.println(response );
return null;
}
}