赞
踩
目录
先来看我们以前利用RestTemplate发起远程调用的代码:
存在下面的问题:
1、引入依赖
- <!-- feign客户端依赖-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
2、添加@EnableFeignClients注解
- @MapperScan("cn.itcast.order.mapper")
- @SpringBootApplication
- @EnableFeignClients
- public class OrderApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(OrderApplication.class, args);
- }
3、编写FeignClient接口
- package cn.itcast.order.clients;
-
- import cn.itcast.order.pojo.User;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
-
- @FeignClient("userservice")
- public interface UserClient {
- @GetMapping("/user/{id}")
- User findById(@PathVariable("id") Long id);
- }
4、使用FeignClient接口中定义的方法代替RestTemplate
- package cn.itcast.order.service;
-
- import cn.itcast.order.clients.UserClient;
- import cn.itcast.order.mapper.OrderMapper;
- import cn.itcast.order.pojo.Order;
- import cn.itcast.order.pojo.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.web.client.RestTemplate;
-
- @Service
- public class OrderService {
-
- @Autowired
- private OrderMapper orderMapper;
-
- @Autowired
- private UserClient userClient;
-
- public Order queryOrderById(Long orderId) {
- // 1.查询订单
- Order order = orderMapper.findById(orderId);
- //2.用Feign远程调用
- User user = userClient.findById(order.getUserId());
- //3.封装user到ORDER
- order.setUser(user);
- // 4.返回
- return order;
- }
在消费者order中的UserClient接口定义的方法和提供者user中controller层的一个方法的提交HTTP方式、返回类型、参数类型、路径都一样
官方不推荐,会导致紧耦合,springMVC不起作用(继承不了参数)
用户访问localhost:10010/user/1是网关的端口10010,请求进入网关,网关无法处理这个业务,就只能基于路由规则去做判断,然后去注册中心拉取服务列表,根据地址、负载均衡找到具体的地址
自定义类,实现gobalFilter,添加@order注解:
- //order注解是用来定义过滤器的顺序,越小优先级越高
- @Order(-1)
- @Component
- public class AuthorizeFileter implements GlobalFilter {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- //1.获取请求参数
- ServerHttpRequest request = exchange.getRequest();
- //2.获取参数中的authorization参数
- MultiValueMap<String, String> params = request.getQueryParams();
- //3.判断参数值是否等于admin
- String authorization = params.getFirst("authorization");
- //4.是的话放行
- if ("admin".equals(authorization)){
- return chain.filter(exchange);
- }
- //5.否则拦截
- //5.1设置状态码
- exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
- //5.2拦截请求
- return exchange.getResponse().setComplete();
- }
- }
跨域:域名不一致就是跨域
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。