Feign
所以我们使用一门新的技术:声明式的http客户端Feign
第一步:引入依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
第二步:开启自动装配功能@EnableFeignClients
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients
public class OrderApplication{public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}
}
第三步:编写FeginClient接口
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 {//设置请求方式,url,返回对象,请求参数@GetMapping("/user/{id}")User findbyID(@PathVariable("id") Long id);
}
第四步:使用接口中自定义的方法
@Service
public class OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate UserClient userClient;public Order queryOrderById(Long orderId) {// 1.查询订单Order order = orderMapper.findById(orderId);// // 2。利用RestTemplate发起http请求,查询用户
// String url = "http://userservice/user/"+order.getUserId();//使用rureka服务名
// User user = restTemplate.getForObject(url, User.class);//2.改成利用feign远程调用User user = userClient.findbyID(order.getUserId());//3. 封装数据order.setUser(user);// 4.返回return order;
Fegin的自定义配置
feign:client:config:default:loggerlevel: FULL
Fegin的性能优化
修改底层客户端为Apache HttpClient方式:
第一步:引入依赖
<!-- httpclient依赖--><dependency><groupId>io.github.openfeign</groupId><artifactId>feign-httpclient</artifactId></dependency>
第二步:配置连接池
feign:httpclient:enabled: true # 支持http的开关max-connections: 200max-connections-per-route: 50
Feign的最佳实践
Gateway
搭建网关
第一步:引入依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- 网关gateway依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency>
第二步:编写网关路由配置及nacos地址
server:port: 10010
spring:application:name: gatewaycloud:nacos:server-addr: localhost:8848 # nacos地址gateway:routes:- id: user-server #路由标识,必须唯一uri: lb://userservice #路由的目标地址predicates: #断言,判断请求是否符合规则- Path=/user/**- id: order-serveruri: lb://orderservicepredicates:- Path=/order/**
路由断言工厂
路由过滤器
对单个路由的过滤器:
对全部路由的过滤器
全局过滤器
自定义类,实现GlobalFilter
@Component
//@Order(-1) //定义优先级
public class AuthorizeFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//1,获取请求参数ServerHttpRequest request = exchange.getRequest();MultiValueMap<String, String> queryParams = request.getQueryParams();//2,获取参数中的authorization参数String authorization = queryParams.getFirst("authorization");//3,判断参数if("admin".equals(authorization)){//4,是放行return chain.filter(exchange);}//5,否拦截exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}//设置优先级@Overridepublic int getOrder() {return -1;}
}
过滤器执行顺序
跨域配置