目录
-
Ribbon:
- 使用eureka的时候不用导入Ribbon的POM依赖,eurekaclient中集成了它。
-
结合RestTemplate进行负载均衡服务调用,首先主启动:@SpringBootApplication @EnableEurekaClient //可以替换当前的负载均衡规则 @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyselfRule.class) public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class,args); } }
- 配置类:
@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
-
controller层通过服务名进行调用:
@RestController @Slf4j public class OrderController { public static final String PAYMENT_SRV = "http://CLOUD-PAYMENT-SERVICE"; @Resource private RestTemplate restTemplate; @PostMapping("/consumer/payment") public CommonResult<Payment> create(Payment payment) { return restTemplate.postForObject(PAYMENT_SRV + "/payment", payment, CommonResult.class); } @GetMapping("consumer/payment/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id){ String data = restTemplate.getForObject(PAYMENT_SRV + "/payment/" + id, String.class); CommonResult<Payment> commonResult = JSONObject.parseObject(data, CommonResult.class); return commonResult; } }
-
OpenFeign:
- 导入POM依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
- 主启动:
@SpringBootApplication @EnableFeignClients public class OrderMain8083 { public static void main(String[] args) { SpringApplication.run(OrderMain8083.class,args); } }
-
客户端新建服务接口:
@FeignClient(value = "CLOUD-PAYMENT-SERVICE") //不需要加@Component注入 public interface PaymentFeignService { @GetMapping("payment/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id); }
-
controller层调用service接口中的方法:
@RestController @Slf4j public class OrderController { @Resource private PaymentFeignService paymentFeignService; @GetMapping("payment/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id){ CommonResult<Payment> payment = paymentFeignService.getPayment(id); return payment; } }
-
OpenFeign的日志打印功能
@Configuration public class LogConfig { @Bean Logger.Level feignLoggerLevel(){ //配置日志信息的详略 return Logger.Level.FULL; } }
//配置文件设置打印的级别 logging: level: com.ljw.springcloudstudy.service.PaymentFeignService: debug