spring-cloud-gateway.md 227.5 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419
Spring 云网关
==========


该项目提供了一个构建在 Spring 生态系统之上的 API 网关,包括: Spring 5、 Spring Boot2 和 Project Reactor。 Spring Cloud Gateway 旨在提供一种简单但有效的方法来路由到 API,并向它们提供跨领域的关注,例如:安全性、监视/度量和弹性。

[](#gateway-starter)[1. How to Include Spring Cloud Gateway](#gateway-starter)
----------

要在项目中包含 Spring 云网关,请使用组 ID 为`org.springframework.cloud`和工件 ID 为`spring-cloud-starter-gateway`的 starter。请参阅[Spring Cloud Project page](https://projects.spring.io/spring-cloud/),以获取有关使用当前 Spring 云发布系列设置构建系统的详细信息。

如果包含启动器,但不希望启用网关,请设置`spring.cloud.gateway.enabled=false`

|   |Spring 云网关是建立在[Spring Boot 2.x](https://spring.io/projects/spring-boot#learn)[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html)[Project Reactor](https://projectreactor.io/docs)之上的。因此,当你使用 Spring 云网关时,许多你熟悉的同步库(例如 Spring 数据和 Spring 安全性)和模式可能不适用,如果你不熟悉这些项目,我们建议你在使用 Spring Cloud Gateway 之前,先阅读他们的文档,以熟悉一些新概念。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Spring 云网关需要由 Spring 启动和 Spring WebFlux 提供的 Netty 运行时。它在传统 Servlet 容器中或构建为 WAR 时不工作。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#glossary)[2. Glossary](#glossary)
----------

* **路线**:网关的基本构件。它由一个 ID、一个目标 URI、一组谓词和一组筛选器定义。如果聚合谓词为 true,则匹配路由。

* **谓词**:这是[Java8 函数谓词](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html)。输入类型为[Spring Framework `ServerWebExchange`](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html)。这使你能够匹配 HTTP 请求中的任何内容,例如标题或参数。

* **过滤器**:这些是用特定工厂构造的[`GatewayFilter`](https://github.com/spring-cloud/spring-cloud-gateway/tree/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/GatewayFilter.java)的实例。在这里,你可以在发送下游请求之前或之后修改请求和响应。

[](#gateway-how-it-works)[3. How It Works](#gateway-how-it-works)
----------

下图提供了 Spring 云网关如何工作的高级概述:

![Spring Cloud Gateway Diagram](./images/spring_cloud_gateway_diagram.png)

客户端向 Spring 云网关提出请求。如果网关处理程序映射确定请求与路由匹配,则将请求发送到网关 Web 处理程序。此处理程序通过特定于该请求的筛选链来运行该请求。用虚线划分过滤器的原因是,过滤器可以在发送代理请求之前和之后运行逻辑。所有的“pre”过滤逻辑都会被执行。然后提出代理请求。在提出代理请求之后,将运行“POST”过滤逻辑。

|   |在没有端口的路由中定义的 URI 分别获得 HTTP 和 HTTPS URI 的默认端口号 80 和 443。|
|---|----------------------------------------------------------------------------------------------------------------------|

[](#configuring-route-predicate-factories-and-gateway-filter-factories)[4.配置路由谓词工厂和网关过滤器工厂](#configuring-route-predicate-factories-and-gateway-filter-factories)
----------

配置谓词和过滤器有两种方法:快捷方式和完全展开的参数。下面的大多数示例都使用了快捷方式。

名称和参数名称将以`code`的形式在每个部分的第一个或两个表示中列出。参数通常按快捷方式配置所需的顺序列出。

### [](#shortcut-configuration)[4.1.快捷方式配置](#shortcut-configuration) ###

快捷方式配置由筛选器名称识别,后面跟着一个等号,后面是用逗号分隔的参数值。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue
```

上一个示例用两个参数定义了`Cookie`路由谓词工厂,cookie 名`mycookie`和要匹配`mycookievalue`的值。

### [](#fully-expanded-arguments)[4.2.完全展开的论证](#fully-expanded-arguments) ###

完全展开的参数看起来更像是带有名称/值对的标准 YAML 配置。通常,会有`name`键和`args`键。`args`键是用于配置谓词或筛选器的键值对的映射。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue
```

这是上面显示的`Cookie`谓词的快捷配置的完整配置。

[](#gateway-request-predicates-factories)[5.路线谓词工厂](#gateway-request-predicates-factories)
----------

Spring 云网关将路由匹配为 Spring WebFlux`HandlerMapping`基础设施的一部分。 Spring 云网关包括许多内置的路由谓词工厂。所有这些谓词在 HTTP 请求的不同属性上匹配。你可以将多个路由谓词工厂与逻辑`and`语句组合在一起。

### [](#the-after-route-predicate-factory)[5.1.后路由谓词工厂](#the-after-route-predicate-factory) ###

`After`路由谓词工厂接受一个参数,一个`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的 DateTime 之后发生的请求。下面的示例配置一个 after 路由谓词:

示例 1.应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何请求后提出的 JAN20,2017 年 17:42 山区时间(丹佛)。

### [](#the-before-route-predicate-factory)[5.2.前路由谓词工厂](#the-before-route-predicate-factory) ###

`Before`路由谓词工厂接受一个参数,a`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的`datetime`之前发生的请求。下面的示例配置一个 before 路由谓词:

示例 2.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何在 JAN20,2017 年 17:42 山区时间(丹佛)之前提出的请求。

### [](#the-between-route-predicate-factory)[5.3.路由谓词之间的工厂](#the-between-route-predicate-factory) ###

`Between`路由谓词工厂接受两个参数,`datetime1``datetime2`,它们是 Java`ZonedDateTime`对象。此谓词匹配发生在`datetime1`之后和`datetime2`之前的请求。`datetime2`参数必须位于`datetime1`之后。下面的示例配置了一个 between 路由谓词:

示例 3.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
```

这条路线符合在 JAN20,2017 年 17:42 山区时间(丹佛)之后和 JAN21,2017 年 17:42 山区时间(丹佛)之前提出的任何请求。这对于维护窗口可能是有用的。

### [](#the-cookie-route-predicate-factory)[5.4.cookie 路由谓词工厂](#the-cookie-route-predicate-factory) ###

`Cookie`路由谓词工厂接受两个参数,cookie`name``regexp`(这是一个 Java 正则表达式)。此谓词匹配具有给定名称且其值与正则表达式匹配的 cookie。下面的示例配置了一个 Cookie 路由谓词工厂:

示例 4.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p
```

此路由匹配具有名为`chocolate`的 cookie 的请求,其值与`ch.p`正则表达式匹配。

### [](#the-header-route-predicate-factory)[5.5.头路由谓词工厂](#the-header-route-predicate-factory) ###

`Header`路由谓词工厂接受两个参数,`header``regexp`(这是一个 Java 正则表达式)。此谓词与具有给定名称的头匹配,其值与正则表达式匹配。下面的示例配置头路由谓词:

示例 5.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
```

如果请求有一个名为`X-Request-Id`的头,其值与`\d+`正则表达式匹配(即它有一个或多个数字的值),则此路由匹配。

### [](#the-host-route-predicate-factory)[5.6.主机路由谓词工厂](#the-host-route-predicate-factory) ###

`Host`路由谓词工厂接受一个参数:主机名列表`patterns`。该模式是一种 Ant 样式的模式,以`.`作为分隔符。此谓词匹配与模式匹配的`Host`头。下面的示例配置了一个主机路由谓词:

示例 6.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org
```

URI 模板变量(如`{sub}.myhost.org`)也受到支持。

如果请求具有`Host`头,其值为`www.somehost.org``beta.somehost.org``www.anotherhost.org`,则此路由匹配。

这个谓词提取 URI 模板变量(例如`sub`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

### [](#the-method-route-predicate-factory)[5.7.路由谓词工厂的方法](#the-method-route-predicate-factory) ###

`Method`路由谓词工厂接受一个`methods`参数,该参数是一个或多个参数:要匹配的 HTTP 方法。下面的示例配置了一个方法路由谓词:

示例 7.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST
```

如果请求方法是`GET``POST`,则此路由匹配。

### [](#the-path-route-predicate-factory)[5.8.路径谓词工厂](#the-path-route-predicate-factory) ###

`Path`路由谓词工厂接受两个参数: Spring `PathMatcher``patterns`的列表和一个名为`matchTrailingSlash`的可选标志(默认为`true`)。下面的示例配置了一个路径路由谓词:

示例 8.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}
```

如果请求路径是:例如:`/red/1``/red/1/``/red/blue``/blue/green`,则此路由匹配。

如果`matchTrailingSlash`被设置为`false`,那么请求路径`/red/1/`将不会被匹配。

这个谓词提取 URI 模板变量(例如`segment`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

一种实用方法(称为`get`)可以使访问这些变量变得更容易。下面的示例展示了如何使用`get`方法:

```
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");
```

### [](#the-query-route-predicate-factory)[5.9.查询路由谓词工厂](#the-query-route-predicate-factory) ###

`Query`路由谓词工厂接受两个参数:一个必需的`param`和一个可选的`regexp`(这是一个 Java 正则表达式)。下面的示例配置一个查询路由谓词:

示例 9.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green
```

如果请求包含`green`查询参数,则前面的路由匹配。

application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.
```

如果请求包含一个`red`查询参数,其值与`gree.`regexp 匹配,则前面的路由匹配,因此`green``greet`将匹配。

### [](#the-remoteaddr-route-predicate-factory)[5.10.RemoteAddr 路由谓词工厂](#the-remoteaddr-route-predicate-factory) ###

`RemoteAddr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。以下示例配置了一个 RemoteAddr 路由谓词:

示例 10.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24
```

如果请求的远程地址是`192.168.1.10`,则此路由匹配。

#### [](#modifying-the-way-remote-addresses-are-resolved)[5.10.1.修改远程地址的解析方式](#modifying-the-way-remote-addresses-are-resolved) ####

默认情况下,RemoteAddr 路由谓词工厂使用来自传入请求的远程地址。如果 Spring 云网关位于代理层的后面,这可能与实际的客户端 IP 地址不匹配。

你可以通过设置自定义`RemoteAddressResolver`来定制远程地址的解析方式。 Spring 云网关带有一个基于[X-forward-for 标头](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)`XForwardedRemoteAddressResolver`的非默认远程地址解析器。

`XForwardedRemoteAddressResolver`有两个静态构造函数方法,它们采用不同的方法实现安全性:

* `XForwardedRemoteAddressResolver::trustAll`返回一个`RemoteAddressResolver`,它总是使用在`X-Forwarded-For`头中找到的第一个 IP 地址。这种方法容易受到欺骗,因为恶意客户端可能会为`X-Forwarded-For`设置初始值,该初始值将被解析器接受。

* `XForwardedRemoteAddressResolver::maxTrustedIndex`获取一个索引,该索引与在 Spring 云网关前运行的受信任基础设施的数量相关。 Spring 如果云网关例如只能通过 HAProxy 访问,那么应该使用 1 的值。如果在访问 Spring 云网关之前需要两次跳可信的基础设施,那么应该使用 2 的值。

考虑以下标头值:

```
X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3
```

以下`maxTrustedIndex`值产生以下远程地址:

|   `maxTrustedIndex`    |结果|
|------------------------|-----------------------------------------------------------|
|[`Integer.MIN_VALUE`,0] |(无效,`IllegalArgumentException`在初始化期间)|
|           1            |                          0.0.0.3                          |
|           2            |                          0.0.0.2                          |
|           3            |                          0.0.0.1                          |
|[4, `Integer.MAX_VALUE`]|                          0.0.0.1                          |

下面的示例展示了如何使用 Java 实现相同的配置:

例 11。gatewayconfig.java

```
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)
```

### [](#the-weight-route-predicate-factory)[5.11.权重路径谓词工厂](#the-weight-route-predicate-factory) ###

`Weight`路由谓词工厂接受两个参数:`group``weight`(一个 INT)。权重是按组计算的。下面的示例配置了权重路由谓词:

示例 12.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
```

此路线将把 80% 的流量转发给[weighthigh.org](https://weighthigh.org),并将 20% 的流量转发给[weighlow.org](https://weighlow.org)

### [](#the-xforwarded-remote-addr-route-predicate-factory)[5.12.XForwarded 远程 addr 路由谓词工厂](#the-xforwarded-remote-addr-route-predicate-factory) ###

`XForwarded Remote Addr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。

此路由谓词允许基于`X-Forwarded-For`HTTP 报头对请求进行过滤。

这可以用于反向代理,例如负载均衡器或 Web 应用程序防火墙,在这些代理中,只有当请求来自由这些反向代理使用的受信任的 IP 地址列表时,才允许请求。

下面的示例配置了一个 XForWardeDremoteaddr 路由谓词:

示例 13.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: xforwarded_remoteaddr_route
        uri: https://example.org
        predicates:
        - XForwardedRemoteAddr=192.168.1.1/24
```

如果`X-Forwarded-For`标头包含`192.168.1.10`,则此路由匹配。

[](#gatewayfilter-factories)[6. `GatewayFilter` Factories](#gatewayfilter-factories)
----------

路由过滤器允许以某种方式修改传入 HTTP 请求或传出 HTTP 响应。路由过滤器的作用域是特定的路由。 Spring 云网关包括许多内置的网关过滤工厂。

|   |有关如何使用以下任何过滤器的更详细示例,请查看[unit tests](https://github.com/spring-cloud/spring-cloud-gateway/tree/master/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/filter/factory)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-addrequestheader-gatewayfilter-factory)[6.1. The `AddRequestHeader` `GatewayFilter` Factory](#the-addrequestheader-gatewayfilter-factory) ###

`AddRequestHeader``GatewayFilter`工厂接受一个`name``value`参数。以下示例配置`AddRequestHeader``GatewayFilter`:

示例 14.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue
```

对于所有匹配的请求,此清单将`X-Request-red:blue`头添加到下游请求的头。

`AddRequestHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestHeader``GatewayFilter`:

示例 15.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}
```

### [](#the-addrequestparameter-gatewayfilter-factory)[6.2. The `AddRequestParameter` `GatewayFilter` Factory](#the-addrequestparameter-gatewayfilter-factory) ###

`AddRequestParameter``GatewayFilter`工厂接受`name``value`参数。下面的示例配置`AddRequestParameter``GatewayFilter`:

示例 16.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue
```

这将为所有匹配的请求将`red=blue`添加到下游请求的查询字符串中。

`AddRequestParameter`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestParameter``GatewayFilter`:

示例 17.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}
```

### [](#the-addresponseheader-gatewayfilter-factory)[6.3. The `AddResponseHeader` `GatewayFilter` Factory](#the-addresponseheader-gatewayfilter-factory) ###

`AddResponseHeader``GatewayFilter`工厂接受一个`name``value`参数。以下示例配置`AddResponseHeader``GatewayFilter`:

示例 18.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue
```

这将为所有匹配的请求向下游响应的头添加`X-Response-Red:Blue`头。

`AddResponseHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置了使用变量的`AddResponseHeader``GatewayFilter`:

示例 19.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}
```

### [](#the-deduperesponseheader-gatewayfilter-factory)[6.4. The `DedupeResponseHeader` `GatewayFilter` Factory](#the-deduperesponseheader-gatewayfilter-factory) ###

DedupeResponseHeader 网关过滤器工厂接受一个`name`参数和一个可选的`strategy`参数。`name`可以包含一个以空格分隔的标题名称列表。以下示例配置`DedupeResponseHeader``GatewayFilter`:

示例 20.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
```

在网关 CORS 逻辑和下游逻辑都添加响应头的情况下,这将删除重复的`Access-Control-Allow-Credentials``Access-Control-Allow-Origin`响应头的值。

`DedupeResponseHeader`过滤器还接受一个可选的`strategy`参数。接受的值是`RETAIN_FIRST`(默认)、`RETAIN_LAST``RETAIN_UNIQUE`

### [](#spring-cloud-circuitbreaker-filter-factory)[6.5. Spring Cloud CircuitBreaker GatewayFilter Factory](#spring-cloud-circuitbreaker-filter-factory) ###

Spring 云断路器网关过滤器工厂使用 Spring 云断路器 API 将网关路由封装在断路器中。 Spring Cloud Circuitbreaker 支持可与 Spring Cloud Gateway 一起使用的多个库。 Spring 云支持开箱即用的弹性 4J。

要启用 Spring 云电路断路器过滤器,你需要在 Classpath 上放置`spring-cloud-starter-circuitbreaker-reactor-resilience4j`。下面的示例配置 Spring 云电路断路器`GatewayFilter`:

示例 21.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker
```

要配置断路器,请参阅你正在使用的底层断路器实现的配置。

* [复原力 4J 文档](https://cloud.spring.io/spring-cloud-circuitbreaker/reference/html/spring-cloud-circuitbreaker.html)

Spring 云电路断路器过滤器还可以接受可选的`fallbackUri`参数。目前,只支持`forward:`模式 URI。如果回退被调用,请求将被转发到与 URI 匹配的控制器。下面的示例配置了这种回退:

示例 22.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
```

下面的列表在 Java 中做了相同的事情:

例 23。application.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

当调用断路器回退时,此示例转发到`/inCaseofFailureUseThis`URI。请注意,此示例还演示了(可选的) Spring 云负载平衡器负载平衡(由目标 URI 上的`lb`前缀定义)。

主要的场景是使用`fallbackUri`在网关应用程序中定义内部控制器或处理程序。但是,你也可以将请求重新路由到外部应用程序中的控制器或处理程序,如下所示:

示例 24.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
```

在此示例中,网关应用程序中没有`fallback`端点或处理程序。然而,在另一个应用程序中有一个,注册在`[localhost:9994](http://localhost:9994)`下。

在请求被转发到 Fallback 的情况下, Spring Cloud Circuitbreaker 网关过滤器还提供了导致它的`Throwable`。它被添加到`ServerWebExchange`中,作为`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR`属性,该属性可以在处理网关应用程序内的回退时使用。

对于外部控制器/处理程序场景,可以添加带有异常详细信息的头。你可以在[FallbackHeaders GatewayFilter 工厂部分](#fallback-headers)中找到有关这样做的更多信息。

#### [](#circuit-breaker-status-codes)[6.5.1.按状态码切断断路器](#circuit-breaker-status-codes) ####

在某些情况下,你可能希望基于从其封装的路由返回的状态码来跳闸断路器。断路器配置对象获取一系列状态代码,如果返回这些代码,将导致断路器跳闸。在设置要跳闸的状态码时,可以使用带有状态码值的整数,也可以使用`HttpStatus`枚举的字符串表示。

示例 25.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"
```

例 26。应用程序.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis").addStatusCode("INTERNAL_SERVER_ERROR"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

### [](#fallback-headers)[6.6. The `FallbackHeaders` `GatewayFilter` Factory](#fallback-headers) ###

`FallbackHeaders`工厂允许你在转发到外部应用程序中的`fallbackUri`的请求的标题中添加 Spring Cloud Circuitbreaker 执行异常详细信息,如下所示:

示例 27.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header
```

在本例中,在运行断路器时发生执行异常后,请求被转发到在`localhost:9994`上运行的应用程序中的`fallback`端点或处理程序。带有异常类型、消息和(如果可用的话)根原因异常类型和消息的头将由`FallbackHeaders`过滤器添加到该请求中。

你可以通过设置以下参数的值(以它们的默认值显示)来覆盖配置中的头的名称:

* `executionExceptionTypeHeaderName``“execution-exception-type”`

* `executionExceptionMessageHeaderName``“execution-exception-message”`

* `rootCauseExceptionTypeHeaderName``“root-cause-exception-type”`

* `rootCauseExceptionMessageHeaderName``“root-cause-exception-message”`

有关断路器和网关的更多信息,请参见[Spring Cloud CircuitBreaker Factory section](#spring-cloud-circuitbreaker-filter-factory)

### [](#the-maprequestheader-gatewayfilter-factory)[6.7. The `MapRequestHeader` `GatewayFilter` Factory](#the-maprequestheader-gatewayfilter-factory) ###

`MapRequestHeader``GatewayFilter`工厂接受`fromHeader``toHeader`参数。它将创建一个新的命名头,并从传入的 HTTP 请求中从现有的命名头中提取该值。如果输入标头不存在,则过滤器不会产生任何影响。如果新的命名标头已经存在,那么它的值将被新的值扩充。以下示例配置`MapRequestHeader`:

示例 28.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red
```

这会将`X-Request-Red:<values>`头添加到下游请求,并从传入的 HTTP 请求的`Blue`头更新其值。

### [](#the-prefixpath-gatewayfilter-factory)[6.8. The `PrefixPath` `GatewayFilter` Factory](#the-prefixpath-gatewayfilter-factory) ###

`PrefixPath``GatewayFilter`工厂接受一个`prefix`参数。下面的示例配置`PrefixPath``GatewayFilter`:

示例 29.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath
```

这将在所有匹配请求的路径前缀`/mypath`。因此,对`/hello`的请求将被发送到`/mypath/hello`

### [](#the-preservehostheader-gatewayfilter-factory)[6.9. The `PreserveHostHeader` `GatewayFilter` Factory](#the-preservehostheader-gatewayfilter-factory) ###

`PreserveHostHeader``GatewayFilter`工厂没有参数。此筛选器设置一个请求属性,由路由筛选器检查该属性,以确定是否应发送原始的主机头,而不是由 HTTP 客户机确定的主机头。以下示例配置`PreserveHostHeader``GatewayFilter`:

示例 30.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader
```

### [](#the-requestratelimiter-gatewayfilter-factory)[6.10. The `RequestRateLimiter` `GatewayFilter` Factory](#the-requestratelimiter-gatewayfilter-factory) ###

`RequestRateLimiter``GatewayFilter`工厂使用`RateLimiter`实现来确定是否允许当前请求继续执行。如果不是,则返回`HTTP 429 - Too Many Requests`(默认情况下)的状态。

这个过滤器接受一个可选的`keyResolver`参数和特定于速率限制器的参数(将在本节后面描述)。

`keyResolver`是实现`KeyResolver`接口的 Bean。在配置中,使用 spel 按名称引用 Bean。`#{@mykeyresolver}` 是引用名为`myKeyResolver`的 Bean 的 spel 表达式。下面的清单显示了`KeyResolver`接口:

例 31。keyresolver.java

```
public interface KeyResolver {
    Mono<String> resolve(ServerWebExchange exchange);
}
```

`KeyResolver`接口让可插入策略派生限制请求的键。在未来的里程碑版本中,将会有一些`KeyResolver`实现。

`KeyResolver`的默认实现是`PrincipalNameKeyResolver`,它从`ServerWebExchange`检索`Principal`并调用`Principal.getName()`

默认情况下,如果`KeyResolver`没有找到密钥,请求将被拒绝。你可以通过设置`spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key``true’或`false`)和`spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code`属性来调整此行为。

|   |`RequestRateLimiter`不能使用“shortcut”符号进行配置。下面的示例是*无效*:<br/><br/>示例 32.application.properties<br/><br/>```<br/># 无效的快捷方式配置<br/> Spring.cloud.gateway.routes[0].filters[0]=requestrateLimiter=2,2,#{@userkeyresolever=“426”/>```|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#the-redis-ratelimiter)[6.10.1. The Redis `RateLimiter`](#the-redis-ratelimiter) ####

Redis 实现基于在[Stripe](https://stripe.com/blog/rate-limiters)上完成的工作。它需要使用`spring-boot-starter-data-redis-reactive` Spring 引导启动器。

使用的算法是[令牌桶算法](https://en.wikipedia.org/wiki/Token_bucket)。

`redis-rate-limiter.replenishRate`属性是你希望用户在不删除任何请求的情况下每秒可以执行多少个请求。这是令牌桶被填满的速率。

`redis-rate-limiter.burstCapacity`属性是用户在一秒钟内被允许执行的最大请求数。这是令牌桶可以容纳的令牌数量。将此值设置为零将阻止所有请求。

`redis-rate-limiter.requestedTokens`属性是一个请求需要多少令牌。这是每个请求从 bucket 中获取的令牌的数量,默认为`1`。

通过在`replenishRate`和`burstCapacity`中设置相同的值,可以实现稳定的速率。可以通过将`burstCapacity`设置为高于`replenishRate`来允许临时突发。在这种情况下,速率限制器需要允许在两次突发之间有一段时间(根据`replenishRate`),因为连续两次突发将导致丢弃请求(`HTTP429-太多请求’)。下面的清单配置了`redis-rate-limiter`:

速率限制`1 request/s`通过将`replenishRate`设置为所需的请求数,`requestedTokens`设置为秒内的时间跨度,`burstCapacity`设置为`replenishRate``requestedTokens`的乘积,例如,设置`replenishRate=1``requestedTokens=60``burstCapacity=60`将导致`1 request/min`的限制。

示例 33.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1
```

下面的示例在 Java 中配置一个 keyresolver:

例 34。config.java

```
@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
```

这定义了每个用户 10 个的请求速率限制。允许突发 20 个请求,但在接下来的一秒钟内,只有 10 个请求可用。`KeyResolver`是一个获得`user`请求参数的简单参数(请注意,这不推荐用于生产)。

还可以将速率限制器定义为实现`RateLimiter`接口的 Bean。在配置中,你可以使用 spel 按名称引用 Bean。`#{@myratelimiter}` 是一个 spel 表达式,它引用名为`myRateLimiter`的 Bean。下面的清单定义了一个速率限制器,该限制器使用上一个清单中定义的`KeyResolver`:

示例 35.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"
```

### [](#the-redirectto-gatewayfilter-factory)[6.11. The `RedirectTo` `GatewayFilter` Factory](#the-redirectto-gatewayfilter-factory) ###

`RedirectTo``GatewayFilter`工厂接受两个参数,`status``url``status`参数应该是 300 系列重定向 HTTP 代码,例如 301。`url`参数应该是一个有效的 URL。这是`Location`标头的值。对于相对重定向,应该使用`uri: no://op`作为路由定义的 URI。下面的列表配置了`RedirectTo``GatewayFilter`:

示例 36.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org
```

这将发送带有`Location:https://acme.org`头的状态 302 来执行重定向。

### [](#the-removerequestheader-gatewayfilter-factory)[6.12. The `RemoveRequestHeader` GatewayFilter Factory](#the-removerequestheader-gatewayfilter-factory) ###

`RemoveRequestHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveRequestHeader``GatewayFilter`:

示例 37.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo
```

这将在向下游发送`X-Request-Foo`头之前删除它。

### [](#removeresponseheader-gatewayfilter-factory)[6.13. `RemoveResponseHeader` `GatewayFilter` Factory](#removeresponseheader-gatewayfilter-factory) ###

`RemoveResponseHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveResponseHeader``GatewayFilter`:

示例 38.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo
```

这将在响应返回到网关客户机之前从响应中删除`X-Response-Foo`头。

要删除任何类型的敏感报头,你应该为你可能想要删除的任何路由配置此筛选器。此外,你可以使用`spring.cloud.gateway.default-filters`配置该过滤器一次,并将其应用于所有路由。

### [](#the-removerequestparameter-gatewayfilter-factory)[6.14. The `RemoveRequestParameter` `GatewayFilter` Factory](#the-removerequestparameter-gatewayfilter-factory) ###

`RemoveRequestParameter``GatewayFilter`工厂接受一个`name`参数。它是要删除的查询参数的名称。下面的示例配置`RemoveRequestParameter``GatewayFilter`:

示例 39.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red
```

这将在向下游发送`red`参数之前删除该参数。

### [](#the-rewritepath-gatewayfilter-factory)[6.15. The `RewritePath` `GatewayFilter` Factory](#the-rewritepath-gatewayfilter-factory) ###

`RewritePath``GatewayFilter`工厂接受一个路径`regexp`参数和一个`replacement`参数。这使用 Java 正则表达式以灵活的方式重写请求路径。下面的列表配置了`RewritePath``GatewayFilter`:

示例 40.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/?(?<segment>.*), /$\{segment}
```

对于`/red/blue`的请求路径,在发出下游请求之前,将路径设置为`/blue`。注意,由于 YAML 规范,`Spring 云网关
==========


该项目提供了一个构建在 Spring 生态系统之上的 API 网关,包括: Spring 5、 Spring Boot2 和 Project Reactor。 Spring Cloud Gateway 旨在提供一种简单但有效的方法来路由到 API,并向它们提供跨领域的关注,例如:安全性、监视/度量和弹性。

[](#gateway-starter)[1. How to Include Spring Cloud Gateway](#gateway-starter)
----------

要在项目中包含 Spring 云网关,请使用组 ID 为`org.springframework.cloud`和工件 ID 为`spring-cloud-starter-gateway`的 starter。请参阅[Spring Cloud Project page](https://projects.spring.io/spring-cloud/),以获取有关使用当前 Spring 云发布系列设置构建系统的详细信息。

如果包含启动器,但不希望启用网关,请设置`spring.cloud.gateway.enabled=false`

|   |Spring 云网关是建立在[Spring Boot 2.x](https://spring.io/projects/spring-boot#learn)[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html)[Project Reactor](https://projectreactor.io/docs)之上的。因此,当你使用 Spring 云网关时,许多你熟悉的同步库(例如 Spring 数据和 Spring 安全性)和模式可能不适用,如果你不熟悉这些项目,我们建议你在使用 Spring Cloud Gateway 之前,先阅读他们的文档,以熟悉一些新概念。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Spring 云网关需要由 Spring 启动和 Spring WebFlux 提供的 Netty 运行时。它在传统 Servlet 容器中或构建为 WAR 时不工作。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#glossary)[2. Glossary](#glossary)
----------

* **路线**:网关的基本构件。它由一个 ID、一个目标 URI、一组谓词和一组筛选器定义。如果聚合谓词为 true,则匹配路由。

* **谓词**:这是[Java8 函数谓词](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html)。输入类型为[Spring Framework `ServerWebExchange`](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html)。这使你能够匹配 HTTP 请求中的任何内容,例如标题或参数。

* **过滤器**:这些是用特定工厂构造的[`GatewayFilter`](https://github.com/spring-cloud/spring-cloud-gateway/tree/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/GatewayFilter.java)的实例。在这里,你可以在发送下游请求之前或之后修改请求和响应。

[](#gateway-how-it-works)[3. How It Works](#gateway-how-it-works)
----------

下图提供了 Spring 云网关如何工作的高级概述:

![Spring Cloud Gateway Diagram](./images/spring_cloud_gateway_diagram.png)

客户端向 Spring 云网关提出请求。如果网关处理程序映射确定请求与路由匹配,则将请求发送到网关 Web 处理程序。此处理程序通过特定于该请求的筛选链来运行该请求。用虚线划分过滤器的原因是,过滤器可以在发送代理请求之前和之后运行逻辑。所有的“pre”过滤逻辑都会被执行。然后提出代理请求。在提出代理请求之后,将运行“POST”过滤逻辑。

|   |在没有端口的路由中定义的 URI 分别获得 HTTP 和 HTTPS URI 的默认端口号 80 和 443。|
|---|----------------------------------------------------------------------------------------------------------------------|

[](#configuring-route-predicate-factories-and-gateway-filter-factories)[4.配置路由谓词工厂和网关过滤器工厂](#configuring-route-predicate-factories-and-gateway-filter-factories)
----------

配置谓词和过滤器有两种方法:快捷方式和完全展开的参数。下面的大多数示例都使用了快捷方式。

名称和参数名称将以`code`的形式在每个部分的第一个或两个表示中列出。参数通常按快捷方式配置所需的顺序列出。

### [](#shortcut-configuration)[4.1.快捷方式配置](#shortcut-configuration) ###

快捷方式配置由筛选器名称识别,后面跟着一个等号,后面是用逗号分隔的参数值。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue
```

上一个示例用两个参数定义了`Cookie`路由谓词工厂,cookie 名`mycookie`和要匹配`mycookievalue`的值。

### [](#fully-expanded-arguments)[4.2.完全展开的论证](#fully-expanded-arguments) ###

完全展开的参数看起来更像是带有名称/值对的标准 YAML 配置。通常,会有`name`键和`args`键。`args`键是用于配置谓词或筛选器的键值对的映射。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue
```

这是上面显示的`Cookie`谓词的快捷配置的完整配置。

[](#gateway-request-predicates-factories)[5.路线谓词工厂](#gateway-request-predicates-factories)
----------

Spring 云网关将路由匹配为 Spring WebFlux`HandlerMapping`基础设施的一部分。 Spring 云网关包括许多内置的路由谓词工厂。所有这些谓词在 HTTP 请求的不同属性上匹配。你可以将多个路由谓词工厂与逻辑`and`语句组合在一起。

### [](#the-after-route-predicate-factory)[5.1.后路由谓词工厂](#the-after-route-predicate-factory) ###

`After`路由谓词工厂接受一个参数,一个`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的 DateTime 之后发生的请求。下面的示例配置一个 after 路由谓词:

示例 1.应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何请求后提出的 JAN20,2017 年 17:42 山区时间(丹佛)。

### [](#the-before-route-predicate-factory)[5.2.前路由谓词工厂](#the-before-route-predicate-factory) ###

`Before`路由谓词工厂接受一个参数,a`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的`datetime`之前发生的请求。下面的示例配置一个 before 路由谓词:

示例 2.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何在 JAN20,2017 年 17:42 山区时间(丹佛)之前提出的请求。

### [](#the-between-route-predicate-factory)[5.3.路由谓词之间的工厂](#the-between-route-predicate-factory) ###

`Between`路由谓词工厂接受两个参数,`datetime1``datetime2`,它们是 Java`ZonedDateTime`对象。此谓词匹配发生在`datetime1`之后和`datetime2`之前的请求。`datetime2`参数必须位于`datetime1`之后。下面的示例配置了一个 between 路由谓词:

示例 3.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
```

这条路线符合在 JAN20,2017 年 17:42 山区时间(丹佛)之后和 JAN21,2017 年 17:42 山区时间(丹佛)之前提出的任何请求。这对于维护窗口可能是有用的。

### [](#the-cookie-route-predicate-factory)[5.4.cookie 路由谓词工厂](#the-cookie-route-predicate-factory) ###

`Cookie`路由谓词工厂接受两个参数,cookie`name``regexp`(这是一个 Java 正则表达式)。此谓词匹配具有给定名称且其值与正则表达式匹配的 cookie。下面的示例配置了一个 Cookie 路由谓词工厂:

示例 4.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p
```

此路由匹配具有名为`chocolate`的 cookie 的请求,其值与`ch.p`正则表达式匹配。

### [](#the-header-route-predicate-factory)[5.5.头路由谓词工厂](#the-header-route-predicate-factory) ###

`Header`路由谓词工厂接受两个参数,`header``regexp`(这是一个 Java 正则表达式)。此谓词与具有给定名称的头匹配,其值与正则表达式匹配。下面的示例配置头路由谓词:

示例 5.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
```

如果请求有一个名为`X-Request-Id`的头,其值与`\d+`正则表达式匹配(即它有一个或多个数字的值),则此路由匹配。

### [](#the-host-route-predicate-factory)[5.6.主机路由谓词工厂](#the-host-route-predicate-factory) ###

`Host`路由谓词工厂接受一个参数:主机名列表`patterns`。该模式是一种 Ant 样式的模式,以`.`作为分隔符。此谓词匹配与模式匹配的`Host`头。下面的示例配置了一个主机路由谓词:

示例 6.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org
```

URI 模板变量(如`{sub}.myhost.org`)也受到支持。

如果请求具有`Host`头,其值为`www.somehost.org``beta.somehost.org``www.anotherhost.org`,则此路由匹配。

这个谓词提取 URI 模板变量(例如`sub`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

### [](#the-method-route-predicate-factory)[5.7.路由谓词工厂的方法](#the-method-route-predicate-factory) ###

`Method`路由谓词工厂接受一个`methods`参数,该参数是一个或多个参数:要匹配的 HTTP 方法。下面的示例配置了一个方法路由谓词:

示例 7.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST
```

如果请求方法是`GET``POST`,则此路由匹配。

### [](#the-path-route-predicate-factory)[5.8.路径谓词工厂](#the-path-route-predicate-factory) ###

`Path`路由谓词工厂接受两个参数: Spring `PathMatcher``patterns`的列表和一个名为`matchTrailingSlash`的可选标志(默认为`true`)。下面的示例配置了一个路径路由谓词:

示例 8.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}
```

如果请求路径是:例如:`/red/1``/red/1/``/red/blue``/blue/green`,则此路由匹配。

如果`matchTrailingSlash`被设置为`false`,那么请求路径`/red/1/`将不会被匹配。

这个谓词提取 URI 模板变量(例如`segment`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

一种实用方法(称为`get`)可以使访问这些变量变得更容易。下面的示例展示了如何使用`get`方法:

```
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");
```

### [](#the-query-route-predicate-factory)[5.9.查询路由谓词工厂](#the-query-route-predicate-factory) ###

`Query`路由谓词工厂接受两个参数:一个必需的`param`和一个可选的`regexp`(这是一个 Java 正则表达式)。下面的示例配置一个查询路由谓词:

示例 9.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green
```

如果请求包含`green`查询参数,则前面的路由匹配。

application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.
```

如果请求包含一个`red`查询参数,其值与`gree.`regexp 匹配,则前面的路由匹配,因此`green``greet`将匹配。

### [](#the-remoteaddr-route-predicate-factory)[5.10.RemoteAddr 路由谓词工厂](#the-remoteaddr-route-predicate-factory) ###

`RemoteAddr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。以下示例配置了一个 RemoteAddr 路由谓词:

示例 10.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24
```

如果请求的远程地址是`192.168.1.10`,则此路由匹配。

#### [](#modifying-the-way-remote-addresses-are-resolved)[5.10.1.修改远程地址的解析方式](#modifying-the-way-remote-addresses-are-resolved) ####

默认情况下,RemoteAddr 路由谓词工厂使用来自传入请求的远程地址。如果 Spring 云网关位于代理层的后面,这可能与实际的客户端 IP 地址不匹配。

你可以通过设置自定义`RemoteAddressResolver`来定制远程地址的解析方式。 Spring 云网关带有一个基于[X-forward-for 标头](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)`XForwardedRemoteAddressResolver`的非默认远程地址解析器。

`XForwardedRemoteAddressResolver`有两个静态构造函数方法,它们采用不同的方法实现安全性:

* `XForwardedRemoteAddressResolver::trustAll`返回一个`RemoteAddressResolver`,它总是使用在`X-Forwarded-For`头中找到的第一个 IP 地址。这种方法容易受到欺骗,因为恶意客户端可能会为`X-Forwarded-For`设置初始值,该初始值将被解析器接受。

* `XForwardedRemoteAddressResolver::maxTrustedIndex`获取一个索引,该索引与在 Spring 云网关前运行的受信任基础设施的数量相关。 Spring 如果云网关例如只能通过 HAProxy 访问,那么应该使用 1 的值。如果在访问 Spring 云网关之前需要两次跳可信的基础设施,那么应该使用 2 的值。

考虑以下标头值:

```
X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3
```

以下`maxTrustedIndex`值产生以下远程地址:

|   `maxTrustedIndex`    |结果|
|------------------------|-----------------------------------------------------------|
|[`Integer.MIN_VALUE`,0] |(无效,`IllegalArgumentException`在初始化期间)|
|           1            |                          0.0.0.3                          |
|           2            |                          0.0.0.2                          |
|           3            |                          0.0.0.1                          |
|[4, `Integer.MAX_VALUE`]|                          0.0.0.1                          |

下面的示例展示了如何使用 Java 实现相同的配置:

例 11。gatewayconfig.java

```
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)
```

### [](#the-weight-route-predicate-factory)[5.11.权重路径谓词工厂](#the-weight-route-predicate-factory) ###

`Weight`路由谓词工厂接受两个参数:`group``weight`(一个 INT)。权重是按组计算的。下面的示例配置了权重路由谓词:

示例 12.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
```

此路线将把 80% 的流量转发给[weighthigh.org](https://weighthigh.org),并将 20% 的流量转发给[weighlow.org](https://weighlow.org)

### [](#the-xforwarded-remote-addr-route-predicate-factory)[5.12.XForwarded 远程 addr 路由谓词工厂](#the-xforwarded-remote-addr-route-predicate-factory) ###

`XForwarded Remote Addr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。

此路由谓词允许基于`X-Forwarded-For`HTTP 报头对请求进行过滤。

这可以用于反向代理,例如负载均衡器或 Web 应用程序防火墙,在这些代理中,只有当请求来自由这些反向代理使用的受信任的 IP 地址列表时,才允许请求。

下面的示例配置了一个 XForWardeDremoteaddr 路由谓词:

示例 13.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: xforwarded_remoteaddr_route
        uri: https://example.org
        predicates:
        - XForwardedRemoteAddr=192.168.1.1/24
```

如果`X-Forwarded-For`标头包含`192.168.1.10`,则此路由匹配。

[](#gatewayfilter-factories)[6. `GatewayFilter` Factories](#gatewayfilter-factories)
----------

路由过滤器允许以某种方式修改传入 HTTP 请求或传出 HTTP 响应。路由过滤器的作用域是特定的路由。 Spring 云网关包括许多内置的网关过滤工厂。

|   |有关如何使用以下任何过滤器的更详细示例,请查看[unit tests](https://github.com/spring-cloud/spring-cloud-gateway/tree/master/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/filter/factory)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-addrequestheader-gatewayfilter-factory)[6.1. The `AddRequestHeader` `GatewayFilter` Factory](#the-addrequestheader-gatewayfilter-factory) ###

`AddRequestHeader``GatewayFilter`工厂接受一个`name``value`参数。以下示例配置`AddRequestHeader``GatewayFilter`:

示例 14.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue
```

对于所有匹配的请求,此清单将`X-Request-red:blue`头添加到下游请求的头。

`AddRequestHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestHeader``GatewayFilter`:

示例 15.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}
```

### [](#the-addrequestparameter-gatewayfilter-factory)[6.2. The `AddRequestParameter` `GatewayFilter` Factory](#the-addrequestparameter-gatewayfilter-factory) ###

`AddRequestParameter``GatewayFilter`工厂接受`name``value`参数。下面的示例配置`AddRequestParameter``GatewayFilter`:

示例 16.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue
```

这将为所有匹配的请求将`red=blue`添加到下游请求的查询字符串中。

`AddRequestParameter`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestParameter``GatewayFilter`:

示例 17.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}
```

### [](#the-addresponseheader-gatewayfilter-factory)[6.3. The `AddResponseHeader` `GatewayFilter` Factory](#the-addresponseheader-gatewayfilter-factory) ###

`AddResponseHeader``GatewayFilter`工厂接受一个`name``value`参数。以下示例配置`AddResponseHeader``GatewayFilter`:

示例 18.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue
```

这将为所有匹配的请求向下游响应的头添加`X-Response-Red:Blue`头。

`AddResponseHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置了使用变量的`AddResponseHeader``GatewayFilter`:

示例 19.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}
```

### [](#the-deduperesponseheader-gatewayfilter-factory)[6.4. The `DedupeResponseHeader` `GatewayFilter` Factory](#the-deduperesponseheader-gatewayfilter-factory) ###

DedupeResponseHeader 网关过滤器工厂接受一个`name`参数和一个可选的`strategy`参数。`name`可以包含一个以空格分隔的标题名称列表。以下示例配置`DedupeResponseHeader``GatewayFilter`:

示例 20.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
```

在网关 CORS 逻辑和下游逻辑都添加响应头的情况下,这将删除重复的`Access-Control-Allow-Credentials``Access-Control-Allow-Origin`响应头的值。

`DedupeResponseHeader`过滤器还接受一个可选的`strategy`参数。接受的值是`RETAIN_FIRST`(默认)、`RETAIN_LAST``RETAIN_UNIQUE`

### [](#spring-cloud-circuitbreaker-filter-factory)[6.5. Spring Cloud CircuitBreaker GatewayFilter Factory](#spring-cloud-circuitbreaker-filter-factory) ###

Spring 云断路器网关过滤器工厂使用 Spring 云断路器 API 将网关路由封装在断路器中。 Spring Cloud Circuitbreaker 支持可与 Spring Cloud Gateway 一起使用的多个库。 Spring 云支持开箱即用的弹性 4J。

要启用 Spring 云电路断路器过滤器,你需要在 Classpath 上放置`spring-cloud-starter-circuitbreaker-reactor-resilience4j`。下面的示例配置 Spring 云电路断路器`GatewayFilter`:

示例 21.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker
```

要配置断路器,请参阅你正在使用的底层断路器实现的配置。

* [复原力 4J 文档](https://cloud.spring.io/spring-cloud-circuitbreaker/reference/html/spring-cloud-circuitbreaker.html)

Spring 云电路断路器过滤器还可以接受可选的`fallbackUri`参数。目前,只支持`forward:`模式 URI。如果回退被调用,请求将被转发到与 URI 匹配的控制器。下面的示例配置了这种回退:

示例 22.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
```

下面的列表在 Java 中做了相同的事情:

例 23。application.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

当调用断路器回退时,此示例转发到`/inCaseofFailureUseThis`URI。请注意,此示例还演示了(可选的) Spring 云负载平衡器负载平衡(由目标 URI 上的`lb`前缀定义)。

主要的场景是使用`fallbackUri`在网关应用程序中定义内部控制器或处理程序。但是,你也可以将请求重新路由到外部应用程序中的控制器或处理程序,如下所示:

示例 24.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
```

在此示例中,网关应用程序中没有`fallback`端点或处理程序。然而,在另一个应用程序中有一个,注册在`[localhost:9994](http://localhost:9994)`下。

在请求被转发到 Fallback 的情况下, Spring Cloud Circuitbreaker 网关过滤器还提供了导致它的`Throwable`。它被添加到`ServerWebExchange`中,作为`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR`属性,该属性可以在处理网关应用程序内的回退时使用。

对于外部控制器/处理程序场景,可以添加带有异常详细信息的头。你可以在[FallbackHeaders GatewayFilter 工厂部分](#fallback-headers)中找到有关这样做的更多信息。

#### [](#circuit-breaker-status-codes)[6.5.1.按状态码切断断路器](#circuit-breaker-status-codes) ####

在某些情况下,你可能希望基于从其封装的路由返回的状态码来跳闸断路器。断路器配置对象获取一系列状态代码,如果返回这些代码,将导致断路器跳闸。在设置要跳闸的状态码时,可以使用带有状态码值的整数,也可以使用`HttpStatus`枚举的字符串表示。

示例 25.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"
```

例 26。应用程序.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis").addStatusCode("INTERNAL_SERVER_ERROR"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

### [](#fallback-headers)[6.6. The `FallbackHeaders` `GatewayFilter` Factory](#fallback-headers) ###

`FallbackHeaders`工厂允许你在转发到外部应用程序中的`fallbackUri`的请求的标题中添加 Spring Cloud Circuitbreaker 执行异常详细信息,如下所示:

示例 27.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header
```

在本例中,在运行断路器时发生执行异常后,请求被转发到在`localhost:9994`上运行的应用程序中的`fallback`端点或处理程序。带有异常类型、消息和(如果可用的话)根原因异常类型和消息的头将由`FallbackHeaders`过滤器添加到该请求中。

你可以通过设置以下参数的值(以它们的默认值显示)来覆盖配置中的头的名称:

* `executionExceptionTypeHeaderName``“execution-exception-type”`

* `executionExceptionMessageHeaderName``“execution-exception-message”`

* `rootCauseExceptionTypeHeaderName``“root-cause-exception-type”`

* `rootCauseExceptionMessageHeaderName``“root-cause-exception-message”`

有关断路器和网关的更多信息,请参见[Spring Cloud CircuitBreaker Factory section](#spring-cloud-circuitbreaker-filter-factory)

### [](#the-maprequestheader-gatewayfilter-factory)[6.7. The `MapRequestHeader` `GatewayFilter` Factory](#the-maprequestheader-gatewayfilter-factory) ###

`MapRequestHeader``GatewayFilter`工厂接受`fromHeader``toHeader`参数。它将创建一个新的命名头,并从传入的 HTTP 请求中从现有的命名头中提取该值。如果输入标头不存在,则过滤器不会产生任何影响。如果新的命名标头已经存在,那么它的值将被新的值扩充。以下示例配置`MapRequestHeader`:

示例 28.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red
```

这会将`X-Request-Red:<values>`头添加到下游请求,并从传入的 HTTP 请求的`Blue`头更新其值。

### [](#the-prefixpath-gatewayfilter-factory)[6.8. The `PrefixPath` `GatewayFilter` Factory](#the-prefixpath-gatewayfilter-factory) ###

`PrefixPath``GatewayFilter`工厂接受一个`prefix`参数。下面的示例配置`PrefixPath``GatewayFilter`:

示例 29.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath
```

这将在所有匹配请求的路径前缀`/mypath`。因此,对`/hello`的请求将被发送到`/mypath/hello`

### [](#the-preservehostheader-gatewayfilter-factory)[6.9. The `PreserveHostHeader` `GatewayFilter` Factory](#the-preservehostheader-gatewayfilter-factory) ###

`PreserveHostHeader``GatewayFilter`工厂没有参数。此筛选器设置一个请求属性,由路由筛选器检查该属性,以确定是否应发送原始的主机头,而不是由 HTTP 客户机确定的主机头。以下示例配置`PreserveHostHeader``GatewayFilter`:

示例 30.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader
```

### [](#the-requestratelimiter-gatewayfilter-factory)[6.10. The `RequestRateLimiter` `GatewayFilter` Factory](#the-requestratelimiter-gatewayfilter-factory) ###

`RequestRateLimiter``GatewayFilter`工厂使用`RateLimiter`实现来确定是否允许当前请求继续执行。如果不是,则返回`HTTP 429 - Too Many Requests`(默认情况下)的状态。

这个过滤器接受一个可选的`keyResolver`参数和特定于速率限制器的参数(将在本节后面描述)。

`keyResolver`是实现`KeyResolver`接口的 Bean。在配置中,使用 spel 按名称引用 Bean。`#{@mykeyresolver}` 是引用名为`myKeyResolver`的 Bean 的 spel 表达式。下面的清单显示了`KeyResolver`接口:

例 31。keyresolver.java

```
public interface KeyResolver {
    Mono<String> resolve(ServerWebExchange exchange);
}
```

`KeyResolver`接口让可插入策略派生限制请求的键。在未来的里程碑版本中,将会有一些`KeyResolver`实现。

`KeyResolver`的默认实现是`PrincipalNameKeyResolver`,它从`ServerWebExchange`检索`Principal`并调用`Principal.getName()`

默认情况下,如果`KeyResolver`没有找到密钥,请求将被拒绝。你可以通过设置`spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key``true’或`false`)和`spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code`属性来调整此行为。

|   |`RequestRateLimiter`不能使用“shortcut”符号进行配置。下面的示例是*无效*:<br/><br/>示例 32.application.properties<br/><br/>```<br/># 无效的快捷方式配置<br/> Spring.cloud.gateway.routes[0].filters[0]=requestrateLimiter=2,2,#{@userkeyresolever=“426”/>```|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#the-redis-ratelimiter)[6.10.1. The Redis `RateLimiter`](#the-redis-ratelimiter) ####

Redis 实现基于在[Stripe](https://stripe.com/blog/rate-limiters)上完成的工作。它需要使用`spring-boot-starter-data-redis-reactive` Spring 引导启动器。

使用的算法是[令牌桶算法](https://en.wikipedia.org/wiki/Token_bucket)。

`redis-rate-limiter.replenishRate`属性是你希望用户在不删除任何请求的情况下每秒可以执行多少个请求。这是令牌桶被填满的速率。

`redis-rate-limiter.burstCapacity`属性是用户在一秒钟内被允许执行的最大请求数。这是令牌桶可以容纳的令牌数量。将此值设置为零将阻止所有请求。

`redis-rate-limiter.requestedTokens`属性是一个请求需要多少令牌。这是每个请求从 bucket 中获取的令牌的数量,默认为`1`。

通过在`replenishRate`和`burstCapacity`中设置相同的值,可以实现稳定的速率。可以通过将`burstCapacity`设置为高于`replenishRate`来允许临时突发。在这种情况下,速率限制器需要允许在两次突发之间有一段时间(根据`replenishRate`),因为连续两次突发将导致丢弃请求(`HTTP429-太多请求’)。下面的清单配置了`redis-rate-limiter`:

速率限制`1 request/s`通过将`replenishRate`设置为所需的请求数,`requestedTokens`设置为秒内的时间跨度,`burstCapacity`设置为`replenishRate``requestedTokens`的乘积,例如,设置`replenishRate=1``requestedTokens=60``burstCapacity=60`将导致`1 request/min`的限制。

示例 33.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1
```

下面的示例在 Java 中配置一个 keyresolver:

例 34。config.java

```
@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
```

这定义了每个用户 10 个的请求速率限制。允许突发 20 个请求,但在接下来的一秒钟内,只有 10 个请求可用。`KeyResolver`是一个获得`user`请求参数的简单参数(请注意,这不推荐用于生产)。

还可以将速率限制器定义为实现`RateLimiter`接口的 Bean。在配置中,你可以使用 spel 按名称引用 Bean。`#{@myratelimiter}` 是一个 spel 表达式,它引用名为`myRateLimiter`的 Bean。下面的清单定义了一个速率限制器,该限制器使用上一个清单中定义的`KeyResolver`:

示例 35.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"
```

### [](#the-redirectto-gatewayfilter-factory)[6.11. The `RedirectTo` `GatewayFilter` Factory](#the-redirectto-gatewayfilter-factory) ###

`RedirectTo``GatewayFilter`工厂接受两个参数,`status``url``status`参数应该是 300 系列重定向 HTTP 代码,例如 301。`url`参数应该是一个有效的 URL。这是`Location`标头的值。对于相对重定向,应该使用`uri: no://op`作为路由定义的 URI。下面的列表配置了`RedirectTo``GatewayFilter`:

示例 36.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org
```

这将发送带有`Location:https://acme.org`头的状态 302 来执行重定向。

### [](#the-removerequestheader-gatewayfilter-factory)[6.12. The `RemoveRequestHeader` GatewayFilter Factory](#the-removerequestheader-gatewayfilter-factory) ###

`RemoveRequestHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveRequestHeader``GatewayFilter`:

示例 37.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo
```

这将在向下游发送`X-Request-Foo`头之前删除它。

### [](#removeresponseheader-gatewayfilter-factory)[6.13. `RemoveResponseHeader` `GatewayFilter` Factory](#removeresponseheader-gatewayfilter-factory) ###

`RemoveResponseHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveResponseHeader``GatewayFilter`:

示例 38.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo
```

这将在响应返回到网关客户机之前从响应中删除`X-Response-Foo`头。

要删除任何类型的敏感报头,你应该为你可能想要删除的任何路由配置此筛选器。此外,你可以使用`spring.cloud.gateway.default-filters`配置该过滤器一次,并将其应用于所有路由。

### [](#the-removerequestparameter-gatewayfilter-factory)[6.14. The `RemoveRequestParameter` `GatewayFilter` Factory](#the-removerequestparameter-gatewayfilter-factory) ###

`RemoveRequestParameter``GatewayFilter`工厂接受一个`name`参数。它是要删除的查询参数的名称。下面的示例配置`RemoveRequestParameter``GatewayFilter`:

示例 39.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red
```

这将在向下游发送`red`参数之前删除该参数。

### [](#the-rewritepath-gatewayfilter-factory)[6.15. The `RewritePath` `GatewayFilter` Factory](#the-rewritepath-gatewayfilter-factory) ###

`RewritePath``GatewayFilter`工厂接受一个路径`regexp`参数和一个`replacement`参数。这使用 Java 正则表达式以灵活的方式重写请求路径。下面的列表配置了`RewritePath``GatewayFilter`:

示例 40.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/?(?<segment>.*), /$\{segment}
```

应该替换为`$\`。

### [](#rewritelocationresponseheader-gatewayfilter-factory)[6.16. `RewriteLocationResponseHeader` `GatewayFilter` Factory](#rewritelocationresponseheader-gatewayfilter-factory) ###

`RewriteLocationResponseHeader``GatewayFilter`工厂修改`Location`响应头的值,通常是为了去掉后台特定的细节。它需要`stripVersionMode`,`locationHeaderName`,`hostValue`和`protocolsRegex`参数。下面的列表配置了`RewriteLocationResponseHeader``GatewayFilter`:

示例 41.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritelocationresponseheader_route
        uri: http://example.org
        filters:
        - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
```

例如,对于`POST [api.example.com/some/object/name](https://api.example.com/some/object/name)`的请求,`Location`的响应头值`[object-service.prod.example.net/v2/some/object/id](https://object-service.prod.example.net/v2/some/object/id)`被重写为`[api.example.com/some/object/id](https://api.example.com/some/object/id)`。

`stripVersionMode`参数有以下可能的值:`NEVER_STRIP`,`AS_IN_REQUEST`(默认),和`ALWAYS_STRIP`。

* `NEVER_STRIP`:即使原始请求路径不包含版本,也不会剥离版本。

* `AS_IN_REQUEST`只有当原始请求路径不包含版本时,才会剥离版本。

* `ALWAYS_STRIP`版本总是被剥离,即使原始请求路径包含版本。

如果提供了`hostValue`参数,则用于替换响应`host:port`头的`host:port`部分。如果没有提供,则使用`Host`请求头的值。

参数`protocolsRegex`必须是一个有效的 regex`String`,协议名称与该 regex 匹配。如果不匹配,过滤器就不会做任何事情。默认值为`http|https|ftp|ftps`。

### [](#the-rewriteresponseheader-gatewayfilter-factory)[6.17. The `RewriteResponseHeader` `GatewayFilter` Factory](#the-rewriteresponseheader-gatewayfilter-factory) ###

`RewriteResponseHeader``GatewayFilter`工厂接受`name`、`regexp`和`replacement`参数。它使用 Java 正则表达式以一种灵活的方式重写响应头值。下面的示例配置`RewriteResponseHeader``GatewayFilter`:

示例 42.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        - RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***
```

对于标头值`/42?user=ford&password=omg!what&flag=true`,在发出下游请求后将其设置为`/42?user=ford&password=***&flag=true`。由于 YAML 规范,你必须使用`$\`表示`Spring 云网关
==========


该项目提供了一个构建在 Spring 生态系统之上的 API 网关,包括: Spring 5、 Spring Boot2 和 Project Reactor。 Spring Cloud Gateway 旨在提供一种简单但有效的方法来路由到 API,并向它们提供跨领域的关注,例如:安全性、监视/度量和弹性。

[](#gateway-starter)[1. How to Include Spring Cloud Gateway](#gateway-starter)
----------

要在项目中包含 Spring 云网关,请使用组 ID 为`org.springframework.cloud`和工件 ID 为`spring-cloud-starter-gateway`的 starter。请参阅[Spring Cloud Project page](https://projects.spring.io/spring-cloud/),以获取有关使用当前 Spring 云发布系列设置构建系统的详细信息。

如果包含启动器,但不希望启用网关,请设置`spring.cloud.gateway.enabled=false`。

|   |Spring 云网关是建立在[Spring Boot 2.x](https://spring.io/projects/spring-boot#learn)、[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html)和[Project Reactor](https://projectreactor.io/docs)之上的。因此,当你使用 Spring 云网关时,许多你熟悉的同步库(例如 Spring 数据和 Spring 安全性)和模式可能不适用,如果你不熟悉这些项目,我们建议你在使用 Spring Cloud Gateway 之前,先阅读他们的文档,以熟悉一些新概念。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Spring 云网关需要由 Spring 启动和 Spring WebFlux 提供的 Netty 运行时。它在传统 Servlet 容器中或构建为 WAR 时不工作。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#glossary)[2. Glossary](#glossary)
----------

* **路线**:网关的基本构件。它由一个 ID、一个目标 URI、一组谓词和一组筛选器定义。如果聚合谓词为 true,则匹配路由。

* **谓词**:这是[Java8 函数谓词](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html)。输入类型为[Spring Framework `ServerWebExchange`](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html)。这使你能够匹配 HTTP 请求中的任何内容,例如标题或参数。

* **过滤器**:这些是用特定工厂构造的[`GatewayFilter`](https://github.com/spring-cloud/spring-cloud-gateway/tree/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/GatewayFilter.java)的实例。在这里,你可以在发送下游请求之前或之后修改请求和响应。

[](#gateway-how-it-works)[3. How It Works](#gateway-how-it-works)
----------

下图提供了 Spring 云网关如何工作的高级概述:

![Spring Cloud Gateway Diagram](./images/spring_cloud_gateway_diagram.png)

客户端向 Spring 云网关提出请求。如果网关处理程序映射确定请求与路由匹配,则将请求发送到网关 Web 处理程序。此处理程序通过特定于该请求的筛选链来运行该请求。用虚线划分过滤器的原因是,过滤器可以在发送代理请求之前和之后运行逻辑。所有的“pre”过滤逻辑都会被执行。然后提出代理请求。在提出代理请求之后,将运行“POST”过滤逻辑。

|   |在没有端口的路由中定义的 URI 分别获得 HTTP 和 HTTPS URI 的默认端口号 80 和 443。|
|---|----------------------------------------------------------------------------------------------------------------------|

[](#configuring-route-predicate-factories-and-gateway-filter-factories)[4.配置路由谓词工厂和网关过滤器工厂](#configuring-route-predicate-factories-and-gateway-filter-factories)
----------

配置谓词和过滤器有两种方法:快捷方式和完全展开的参数。下面的大多数示例都使用了快捷方式。

名称和参数名称将以`code`的形式在每个部分的第一个或两个表示中列出。参数通常按快捷方式配置所需的顺序列出。

### [](#shortcut-configuration)[4.1.快捷方式配置](#shortcut-configuration) ###

快捷方式配置由筛选器名称识别,后面跟着一个等号,后面是用逗号分隔的参数值。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue
```

上一个示例用两个参数定义了`Cookie`路由谓词工厂,cookie 名`mycookie`和要匹配`mycookievalue`的值。

### [](#fully-expanded-arguments)[4.2.完全展开的论证](#fully-expanded-arguments) ###

完全展开的参数看起来更像是带有名称/值对的标准 YAML 配置。通常,会有`name`键和`args`键。`args`键是用于配置谓词或筛选器的键值对的映射。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue
```

这是上面显示的`Cookie`谓词的快捷配置的完整配置。

[](#gateway-request-predicates-factories)[5.路线谓词工厂](#gateway-request-predicates-factories)
----------

Spring 云网关将路由匹配为 Spring WebFlux`HandlerMapping`基础设施的一部分。 Spring 云网关包括许多内置的路由谓词工厂。所有这些谓词在 HTTP 请求的不同属性上匹配。你可以将多个路由谓词工厂与逻辑`and`语句组合在一起。

### [](#the-after-route-predicate-factory)[5.1.后路由谓词工厂](#the-after-route-predicate-factory) ###

`After`路由谓词工厂接受一个参数,一个`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的 DateTime 之后发生的请求。下面的示例配置一个 after 路由谓词:

示例 1.应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何请求后提出的 JAN20,2017 年 17:42 山区时间(丹佛)。

### [](#the-before-route-predicate-factory)[5.2.前路由谓词工厂](#the-before-route-predicate-factory) ###

`Before`路由谓词工厂接受一个参数,a`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的`datetime`之前发生的请求。下面的示例配置一个 before 路由谓词:

示例 2.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何在 JAN20,2017 年 17:42 山区时间(丹佛)之前提出的请求。

### [](#the-between-route-predicate-factory)[5.3.路由谓词之间的工厂](#the-between-route-predicate-factory) ###

`Between`路由谓词工厂接受两个参数,`datetime1`和`datetime2`,它们是 Java`ZonedDateTime`对象。此谓词匹配发生在`datetime1`之后和`datetime2`之前的请求。`datetime2`参数必须位于`datetime1`之后。下面的示例配置了一个 between 路由谓词:

示例 3.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
```

这条路线符合在 JAN20,2017 年 17:42 山区时间(丹佛)之后和 JAN21,2017 年 17:42 山区时间(丹佛)之前提出的任何请求。这对于维护窗口可能是有用的。

### [](#the-cookie-route-predicate-factory)[5.4.cookie 路由谓词工厂](#the-cookie-route-predicate-factory) ###

`Cookie`路由谓词工厂接受两个参数,cookie`name`和`regexp`(这是一个 Java 正则表达式)。此谓词匹配具有给定名称且其值与正则表达式匹配的 cookie。下面的示例配置了一个 Cookie 路由谓词工厂:

示例 4.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p
```

此路由匹配具有名为`chocolate`的 cookie 的请求,其值与`ch.p`正则表达式匹配。

### [](#the-header-route-predicate-factory)[5.5.头路由谓词工厂](#the-header-route-predicate-factory) ###

`Header`路由谓词工厂接受两个参数,`header`和`regexp`(这是一个 Java 正则表达式)。此谓词与具有给定名称的头匹配,其值与正则表达式匹配。下面的示例配置头路由谓词:

示例 5.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
```

如果请求有一个名为`X-Request-Id`的头,其值与`\d+`正则表达式匹配(即它有一个或多个数字的值),则此路由匹配。

### [](#the-host-route-predicate-factory)[5.6.主机路由谓词工厂](#the-host-route-predicate-factory) ###

`Host`路由谓词工厂接受一个参数:主机名列表`patterns`。该模式是一种 Ant 样式的模式,以`.`作为分隔符。此谓词匹配与模式匹配的`Host`头。下面的示例配置了一个主机路由谓词:

示例 6.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org
```

URI 模板变量(如`{sub}.myhost.org`)也受到支持。

如果请求具有`Host`头,其值为`www.somehost.org`或`beta.somehost.org`或`www.anotherhost.org`,则此路由匹配。

这个谓词提取 URI 模板变量(例如`sub`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

### [](#the-method-route-predicate-factory)[5.7.路由谓词工厂的方法](#the-method-route-predicate-factory) ###

`Method`路由谓词工厂接受一个`methods`参数,该参数是一个或多个参数:要匹配的 HTTP 方法。下面的示例配置了一个方法路由谓词:

示例 7.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST
```

如果请求方法是`GET`或`POST`,则此路由匹配。

### [](#the-path-route-predicate-factory)[5.8.路径谓词工厂](#the-path-route-predicate-factory) ###

`Path`路由谓词工厂接受两个参数: Spring `PathMatcher``patterns`的列表和一个名为`matchTrailingSlash`的可选标志(默认为`true`)。下面的示例配置了一个路径路由谓词:

示例 8.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}
```

如果请求路径是:例如:`/red/1`或`/red/1/`或`/red/blue`或`/blue/green`,则此路由匹配。

如果`matchTrailingSlash`被设置为`false`,那么请求路径`/red/1/`将不会被匹配。

这个谓词提取 URI 模板变量(例如`segment`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

一种实用方法(称为`get`)可以使访问这些变量变得更容易。下面的示例展示了如何使用`get`方法:

```
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");
```

### [](#the-query-route-predicate-factory)[5.9.查询路由谓词工厂](#the-query-route-predicate-factory) ###

`Query`路由谓词工厂接受两个参数:一个必需的`param`和一个可选的`regexp`(这是一个 Java 正则表达式)。下面的示例配置一个查询路由谓词:

示例 9.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green
```

如果请求包含`green`查询参数,则前面的路由匹配。

application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.
```

如果请求包含一个`red`查询参数,其值与`gree.`regexp 匹配,则前面的路由匹配,因此`green`和`greet`将匹配。

### [](#the-remoteaddr-route-predicate-factory)[5.10.RemoteAddr 路由谓词工厂](#the-remoteaddr-route-predicate-factory) ###

`RemoteAddr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。以下示例配置了一个 RemoteAddr 路由谓词:

示例 10.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24
```

如果请求的远程地址是`192.168.1.10`,则此路由匹配。

#### [](#modifying-the-way-remote-addresses-are-resolved)[5.10.1.修改远程地址的解析方式](#modifying-the-way-remote-addresses-are-resolved) ####

默认情况下,RemoteAddr 路由谓词工厂使用来自传入请求的远程地址。如果 Spring 云网关位于代理层的后面,这可能与实际的客户端 IP 地址不匹配。

你可以通过设置自定义`RemoteAddressResolver`来定制远程地址的解析方式。 Spring 云网关带有一个基于[X-forward-for 标头](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For),`XForwardedRemoteAddressResolver`的非默认远程地址解析器。

`XForwardedRemoteAddressResolver`有两个静态构造函数方法,它们采用不同的方法实现安全性:

* `XForwardedRemoteAddressResolver::trustAll`返回一个`RemoteAddressResolver`,它总是使用在`X-Forwarded-For`头中找到的第一个 IP 地址。这种方法容易受到欺骗,因为恶意客户端可能会为`X-Forwarded-For`设置初始值,该初始值将被解析器接受。

* `XForwardedRemoteAddressResolver::maxTrustedIndex`获取一个索引,该索引与在 Spring 云网关前运行的受信任基础设施的数量相关。 Spring 如果云网关例如只能通过 HAProxy 访问,那么应该使用 1 的值。如果在访问 Spring 云网关之前需要两次跳可信的基础设施,那么应该使用 2 的值。

考虑以下标头值:

```
X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3
```

以下`maxTrustedIndex`值产生以下远程地址:

|   `maxTrustedIndex`    |结果|
|------------------------|-----------------------------------------------------------|
|[`Integer.MIN_VALUE`,0] |(无效,`IllegalArgumentException`在初始化期间)|
|           1            |                          0.0.0.3                          |
|           2            |                          0.0.0.2                          |
|           3            |                          0.0.0.1                          |
|[4, `Integer.MAX_VALUE`]|                          0.0.0.1                          |

下面的示例展示了如何使用 Java 实现相同的配置:

例 11。gatewayconfig.java

```
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)
```

### [](#the-weight-route-predicate-factory)[5.11.权重路径谓词工厂](#the-weight-route-predicate-factory) ###

`Weight`路由谓词工厂接受两个参数:`group`和`weight`(一个 INT)。权重是按组计算的。下面的示例配置了权重路由谓词:

示例 12.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
```

此路线将把 80% 的流量转发给[weighthigh.org](https://weighthigh.org),并将 20% 的流量转发给[weighlow.org](https://weighlow.org)。

### [](#the-xforwarded-remote-addr-route-predicate-factory)[5.12.XForwarded 远程 addr 路由谓词工厂](#the-xforwarded-remote-addr-route-predicate-factory) ###

`XForwarded Remote Addr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。

此路由谓词允许基于`X-Forwarded-For`HTTP 报头对请求进行过滤。

这可以用于反向代理,例如负载均衡器或 Web 应用程序防火墙,在这些代理中,只有当请求来自由这些反向代理使用的受信任的 IP 地址列表时,才允许请求。

下面的示例配置了一个 XForWardeDremoteaddr 路由谓词:

示例 13.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: xforwarded_remoteaddr_route
        uri: https://example.org
        predicates:
        - XForwardedRemoteAddr=192.168.1.1/24
```

如果`X-Forwarded-For`标头包含`192.168.1.10`,则此路由匹配。

[](#gatewayfilter-factories)[6. `GatewayFilter` Factories](#gatewayfilter-factories)
----------

路由过滤器允许以某种方式修改传入 HTTP 请求或传出 HTTP 响应。路由过滤器的作用域是特定的路由。 Spring 云网关包括许多内置的网关过滤工厂。

|   |有关如何使用以下任何过滤器的更详细示例,请查看[unit tests](https://github.com/spring-cloud/spring-cloud-gateway/tree/master/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/filter/factory)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-addrequestheader-gatewayfilter-factory)[6.1. The `AddRequestHeader` `GatewayFilter` Factory](#the-addrequestheader-gatewayfilter-factory) ###

`AddRequestHeader``GatewayFilter`工厂接受一个`name`和`value`参数。以下示例配置`AddRequestHeader``GatewayFilter`:

示例 14.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue
```

对于所有匹配的请求,此清单将`X-Request-red:blue`头添加到下游请求的头。

`AddRequestHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestHeader``GatewayFilter`:

示例 15.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}
```

### [](#the-addrequestparameter-gatewayfilter-factory)[6.2. The `AddRequestParameter` `GatewayFilter` Factory](#the-addrequestparameter-gatewayfilter-factory) ###

`AddRequestParameter``GatewayFilter`工厂接受`name`和`value`参数。下面的示例配置`AddRequestParameter``GatewayFilter`:

示例 16.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue
```

这将为所有匹配的请求将`red=blue`添加到下游请求的查询字符串中。

`AddRequestParameter`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestParameter``GatewayFilter`:

示例 17.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}
```

### [](#the-addresponseheader-gatewayfilter-factory)[6.3. The `AddResponseHeader` `GatewayFilter` Factory](#the-addresponseheader-gatewayfilter-factory) ###

`AddResponseHeader``GatewayFilter`工厂接受一个`name`和`value`参数。以下示例配置`AddResponseHeader``GatewayFilter`:

示例 18.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue
```

这将为所有匹配的请求向下游响应的头添加`X-Response-Red:Blue`头。

`AddResponseHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置了使用变量的`AddResponseHeader``GatewayFilter`:

示例 19.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}
```

### [](#the-deduperesponseheader-gatewayfilter-factory)[6.4. The `DedupeResponseHeader` `GatewayFilter` Factory](#the-deduperesponseheader-gatewayfilter-factory) ###

DedupeResponseHeader 网关过滤器工厂接受一个`name`参数和一个可选的`strategy`参数。`name`可以包含一个以空格分隔的标题名称列表。以下示例配置`DedupeResponseHeader``GatewayFilter`:

示例 20.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
```

在网关 CORS 逻辑和下游逻辑都添加响应头的情况下,这将删除重复的`Access-Control-Allow-Credentials`和`Access-Control-Allow-Origin`响应头的值。

`DedupeResponseHeader`过滤器还接受一个可选的`strategy`参数。接受的值是`RETAIN_FIRST`(默认)、`RETAIN_LAST`和`RETAIN_UNIQUE`。

### [](#spring-cloud-circuitbreaker-filter-factory)[6.5. Spring Cloud CircuitBreaker GatewayFilter Factory](#spring-cloud-circuitbreaker-filter-factory) ###

Spring 云断路器网关过滤器工厂使用 Spring 云断路器 API 将网关路由封装在断路器中。 Spring Cloud Circuitbreaker 支持可与 Spring Cloud Gateway 一起使用的多个库。 Spring 云支持开箱即用的弹性 4J。

要启用 Spring 云电路断路器过滤器,你需要在 Classpath 上放置`spring-cloud-starter-circuitbreaker-reactor-resilience4j`。下面的示例配置 Spring 云电路断路器`GatewayFilter`:

示例 21.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker
```

要配置断路器,请参阅你正在使用的底层断路器实现的配置。

* [复原力 4J 文档](https://cloud.spring.io/spring-cloud-circuitbreaker/reference/html/spring-cloud-circuitbreaker.html)

Spring 云电路断路器过滤器还可以接受可选的`fallbackUri`参数。目前,只支持`forward:`模式 URI。如果回退被调用,请求将被转发到与 URI 匹配的控制器。下面的示例配置了这种回退:

示例 22.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
```

下面的列表在 Java 中做了相同的事情:

例 23。application.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

当调用断路器回退时,此示例转发到`/inCaseofFailureUseThis`URI。请注意,此示例还演示了(可选的) Spring 云负载平衡器负载平衡(由目标 URI 上的`lb`前缀定义)。

主要的场景是使用`fallbackUri`在网关应用程序中定义内部控制器或处理程序。但是,你也可以将请求重新路由到外部应用程序中的控制器或处理程序,如下所示:

示例 24.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
```

在此示例中,网关应用程序中没有`fallback`端点或处理程序。然而,在另一个应用程序中有一个,注册在`[localhost:9994](http://localhost:9994)`下。

在请求被转发到 Fallback 的情况下, Spring Cloud Circuitbreaker 网关过滤器还提供了导致它的`Throwable`。它被添加到`ServerWebExchange`中,作为`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR`属性,该属性可以在处理网关应用程序内的回退时使用。

对于外部控制器/处理程序场景,可以添加带有异常详细信息的头。你可以在[FallbackHeaders GatewayFilter 工厂部分](#fallback-headers)中找到有关这样做的更多信息。

#### [](#circuit-breaker-status-codes)[6.5.1.按状态码切断断路器](#circuit-breaker-status-codes) ####

在某些情况下,你可能希望基于从其封装的路由返回的状态码来跳闸断路器。断路器配置对象获取一系列状态代码,如果返回这些代码,将导致断路器跳闸。在设置要跳闸的状态码时,可以使用带有状态码值的整数,也可以使用`HttpStatus`枚举的字符串表示。

示例 25.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"
```

例 26。应用程序.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis").addStatusCode("INTERNAL_SERVER_ERROR"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

### [](#fallback-headers)[6.6. The `FallbackHeaders` `GatewayFilter` Factory](#fallback-headers) ###

`FallbackHeaders`工厂允许你在转发到外部应用程序中的`fallbackUri`的请求的标题中添加 Spring Cloud Circuitbreaker 执行异常详细信息,如下所示:

示例 27.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header
```

在本例中,在运行断路器时发生执行异常后,请求被转发到在`localhost:9994`上运行的应用程序中的`fallback`端点或处理程序。带有异常类型、消息和(如果可用的话)根原因异常类型和消息的头将由`FallbackHeaders`过滤器添加到该请求中。

你可以通过设置以下参数的值(以它们的默认值显示)来覆盖配置中的头的名称:

* `executionExceptionTypeHeaderName`(`“execution-exception-type”`)

* `executionExceptionMessageHeaderName`(`“execution-exception-message”`)

* `rootCauseExceptionTypeHeaderName`(`“root-cause-exception-type”`)

* `rootCauseExceptionMessageHeaderName`(`“root-cause-exception-message”`)

有关断路器和网关的更多信息,请参见[Spring Cloud CircuitBreaker Factory section](#spring-cloud-circuitbreaker-filter-factory)。

### [](#the-maprequestheader-gatewayfilter-factory)[6.7. The `MapRequestHeader` `GatewayFilter` Factory](#the-maprequestheader-gatewayfilter-factory) ###

`MapRequestHeader``GatewayFilter`工厂接受`fromHeader`和`toHeader`参数。它将创建一个新的命名头,并从传入的 HTTP 请求中从现有的命名头中提取该值。如果输入标头不存在,则过滤器不会产生任何影响。如果新的命名标头已经存在,那么它的值将被新的值扩充。以下示例配置`MapRequestHeader`:

示例 28.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red
```

这会将`X-Request-Red:<values>`头添加到下游请求,并从传入的 HTTP 请求的`Blue`头更新其值。

### [](#the-prefixpath-gatewayfilter-factory)[6.8. The `PrefixPath` `GatewayFilter` Factory](#the-prefixpath-gatewayfilter-factory) ###

`PrefixPath``GatewayFilter`工厂接受一个`prefix`参数。下面的示例配置`PrefixPath``GatewayFilter`:

示例 29.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath
```

这将在所有匹配请求的路径前缀`/mypath`。因此,对`/hello`的请求将被发送到`/mypath/hello`。

### [](#the-preservehostheader-gatewayfilter-factory)[6.9. The `PreserveHostHeader` `GatewayFilter` Factory](#the-preservehostheader-gatewayfilter-factory) ###

`PreserveHostHeader``GatewayFilter`工厂没有参数。此筛选器设置一个请求属性,由路由筛选器检查该属性,以确定是否应发送原始的主机头,而不是由 HTTP 客户机确定的主机头。以下示例配置`PreserveHostHeader``GatewayFilter`:

示例 30.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader
```

### [](#the-requestratelimiter-gatewayfilter-factory)[6.10. The `RequestRateLimiter` `GatewayFilter` Factory](#the-requestratelimiter-gatewayfilter-factory) ###

`RequestRateLimiter``GatewayFilter`工厂使用`RateLimiter`实现来确定是否允许当前请求继续执行。如果不是,则返回`HTTP 429 - Too Many Requests`(默认情况下)的状态。

这个过滤器接受一个可选的`keyResolver`参数和特定于速率限制器的参数(将在本节后面描述)。

`keyResolver`是实现`KeyResolver`接口的 Bean。在配置中,使用 spel 按名称引用 Bean。`#{@mykeyresolver}` 是引用名为`myKeyResolver`的 Bean 的 spel 表达式。下面的清单显示了`KeyResolver`接口:

例 31。keyresolver.java

```
public interface KeyResolver {
    Mono<String> resolve(ServerWebExchange exchange);
}
```

`KeyResolver`接口让可插入策略派生限制请求的键。在未来的里程碑版本中,将会有一些`KeyResolver`实现。

`KeyResolver`的默认实现是`PrincipalNameKeyResolver`,它从`ServerWebExchange`检索`Principal`并调用`Principal.getName()`。

默认情况下,如果`KeyResolver`没有找到密钥,请求将被拒绝。你可以通过设置`spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key`(`true’或`false`)和`spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code`属性来调整此行为。

|   |`RequestRateLimiter`不能使用“shortcut”符号进行配置。下面的示例是*无效*:<br/><br/>示例 32.application.properties<br/><br/>```<br/># 无效的快捷方式配置<br/> Spring.cloud.gateway.routes[0].filters[0]=requestrateLimiter=2,2,#{@userkeyresolever=“426”/>```|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#the-redis-ratelimiter)[6.10.1. The Redis `RateLimiter`](#the-redis-ratelimiter) ####

Redis 实现基于在[Stripe](https://stripe.com/blog/rate-limiters)上完成的工作。它需要使用`spring-boot-starter-data-redis-reactive` Spring 引导启动器。

使用的算法是[令牌桶算法](https://en.wikipedia.org/wiki/Token_bucket)。

`redis-rate-limiter.replenishRate`属性是你希望用户在不删除任何请求的情况下每秒可以执行多少个请求。这是令牌桶被填满的速率。

`redis-rate-limiter.burstCapacity`属性是用户在一秒钟内被允许执行的最大请求数。这是令牌桶可以容纳的令牌数量。将此值设置为零将阻止所有请求。

`redis-rate-limiter.requestedTokens`属性是一个请求需要多少令牌。这是每个请求从 bucket 中获取的令牌的数量,默认为`1`。

通过在`replenishRate`和`burstCapacity`中设置相同的值,可以实现稳定的速率。可以通过将`burstCapacity`设置为高于`replenishRate`来允许临时突发。在这种情况下,速率限制器需要允许在两次突发之间有一段时间(根据`replenishRate`),因为连续两次突发将导致丢弃请求(`HTTP429-太多请求’)。下面的清单配置了`redis-rate-limiter`:

速率限制`1 request/s`通过将`replenishRate`设置为所需的请求数,`requestedTokens`设置为秒内的时间跨度,`burstCapacity`设置为`replenishRate`和`requestedTokens`的乘积,例如,设置`replenishRate=1`,`requestedTokens=60`和`burstCapacity=60`将导致`1 request/min`的限制。

示例 33.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1
```

下面的示例在 Java 中配置一个 keyresolver:

例 34。config.java

```
@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
```

这定义了每个用户 10 个的请求速率限制。允许突发 20 个请求,但在接下来的一秒钟内,只有 10 个请求可用。`KeyResolver`是一个获得`user`请求参数的简单参数(请注意,这不推荐用于生产)。

还可以将速率限制器定义为实现`RateLimiter`接口的 Bean。在配置中,你可以使用 spel 按名称引用 Bean。`#{@myratelimiter}` 是一个 spel 表达式,它引用名为`myRateLimiter`的 Bean。下面的清单定义了一个速率限制器,该限制器使用上一个清单中定义的`KeyResolver`:

示例 35.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"
```

### [](#the-redirectto-gatewayfilter-factory)[6.11. The `RedirectTo` `GatewayFilter` Factory](#the-redirectto-gatewayfilter-factory) ###

`RedirectTo``GatewayFilter`工厂接受两个参数,`status`和`url`。`status`参数应该是 300 系列重定向 HTTP 代码,例如 301。`url`参数应该是一个有效的 URL。这是`Location`标头的值。对于相对重定向,应该使用`uri: no://op`作为路由定义的 URI。下面的列表配置了`RedirectTo``GatewayFilter`:

示例 36.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org
```

这将发送带有`Location:https://acme.org`头的状态 302 来执行重定向。

### [](#the-removerequestheader-gatewayfilter-factory)[6.12. The `RemoveRequestHeader` GatewayFilter Factory](#the-removerequestheader-gatewayfilter-factory) ###

`RemoveRequestHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveRequestHeader``GatewayFilter`:

示例 37.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo
```

这将在向下游发送`X-Request-Foo`头之前删除它。

### [](#removeresponseheader-gatewayfilter-factory)[6.13. `RemoveResponseHeader` `GatewayFilter` Factory](#removeresponseheader-gatewayfilter-factory) ###

`RemoveResponseHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveResponseHeader``GatewayFilter`:

示例 38.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo
```

这将在响应返回到网关客户机之前从响应中删除`X-Response-Foo`头。

要删除任何类型的敏感报头,你应该为你可能想要删除的任何路由配置此筛选器。此外,你可以使用`spring.cloud.gateway.default-filters`配置该过滤器一次,并将其应用于所有路由。

### [](#the-removerequestparameter-gatewayfilter-factory)[6.14. The `RemoveRequestParameter` `GatewayFilter` Factory](#the-removerequestparameter-gatewayfilter-factory) ###

`RemoveRequestParameter``GatewayFilter`工厂接受一个`name`参数。它是要删除的查询参数的名称。下面的示例配置`RemoveRequestParameter``GatewayFilter`:

示例 39.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red
```

这将在向下游发送`red`参数之前删除该参数。

### [](#the-rewritepath-gatewayfilter-factory)[6.15. The `RewritePath` `GatewayFilter` Factory](#the-rewritepath-gatewayfilter-factory) ###

`RewritePath``GatewayFilter`工厂接受一个路径`regexp`参数和一个`replacement`参数。这使用 Java 正则表达式以灵活的方式重写请求路径。下面的列表配置了`RewritePath``GatewayFilter`:

示例 40.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/?(?<segment>.*), /$\{segment}
```

对于`/red/blue`的请求路径,在发出下游请求之前,将路径设置为`/blue`。注意,由于 YAML 规范,`Spring 云网关
==========


该项目提供了一个构建在 Spring 生态系统之上的 API 网关,包括: Spring 5、 Spring Boot2 和 Project Reactor。 Spring Cloud Gateway 旨在提供一种简单但有效的方法来路由到 API,并向它们提供跨领域的关注,例如:安全性、监视/度量和弹性。

[](#gateway-starter)[1. How to Include Spring Cloud Gateway](#gateway-starter)
----------

要在项目中包含 Spring 云网关,请使用组 ID 为`org.springframework.cloud`和工件 ID 为`spring-cloud-starter-gateway`的 starter。请参阅[Spring Cloud Project page](https://projects.spring.io/spring-cloud/),以获取有关使用当前 Spring 云发布系列设置构建系统的详细信息。

如果包含启动器,但不希望启用网关,请设置`spring.cloud.gateway.enabled=false`。

|   |Spring 云网关是建立在[Spring Boot 2.x](https://spring.io/projects/spring-boot#learn)、[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html)和[Project Reactor](https://projectreactor.io/docs)之上的。因此,当你使用 Spring 云网关时,许多你熟悉的同步库(例如 Spring 数据和 Spring 安全性)和模式可能不适用,如果你不熟悉这些项目,我们建议你在使用 Spring Cloud Gateway 之前,先阅读他们的文档,以熟悉一些新概念。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Spring 云网关需要由 Spring 启动和 Spring WebFlux 提供的 Netty 运行时。它在传统 Servlet 容器中或构建为 WAR 时不工作。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#glossary)[2. Glossary](#glossary)
----------

* **路线**:网关的基本构件。它由一个 ID、一个目标 URI、一组谓词和一组筛选器定义。如果聚合谓词为 true,则匹配路由。

* **谓词**:这是[Java8 函数谓词](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html)。输入类型为[Spring Framework `ServerWebExchange`](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html)。这使你能够匹配 HTTP 请求中的任何内容,例如标题或参数。

* **过滤器**:这些是用特定工厂构造的[`GatewayFilter`](https://github.com/spring-cloud/spring-cloud-gateway/tree/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/GatewayFilter.java)的实例。在这里,你可以在发送下游请求之前或之后修改请求和响应。

[](#gateway-how-it-works)[3. How It Works](#gateway-how-it-works)
----------

下图提供了 Spring 云网关如何工作的高级概述:

![Spring Cloud Gateway Diagram](./images/spring_cloud_gateway_diagram.png)

客户端向 Spring 云网关提出请求。如果网关处理程序映射确定请求与路由匹配,则将请求发送到网关 Web 处理程序。此处理程序通过特定于该请求的筛选链来运行该请求。用虚线划分过滤器的原因是,过滤器可以在发送代理请求之前和之后运行逻辑。所有的“pre”过滤逻辑都会被执行。然后提出代理请求。在提出代理请求之后,将运行“POST”过滤逻辑。

|   |在没有端口的路由中定义的 URI 分别获得 HTTP 和 HTTPS URI 的默认端口号 80 和 443。|
|---|----------------------------------------------------------------------------------------------------------------------|

[](#configuring-route-predicate-factories-and-gateway-filter-factories)[4.配置路由谓词工厂和网关过滤器工厂](#configuring-route-predicate-factories-and-gateway-filter-factories)
----------

配置谓词和过滤器有两种方法:快捷方式和完全展开的参数。下面的大多数示例都使用了快捷方式。

名称和参数名称将以`code`的形式在每个部分的第一个或两个表示中列出。参数通常按快捷方式配置所需的顺序列出。

### [](#shortcut-configuration)[4.1.快捷方式配置](#shortcut-configuration) ###

快捷方式配置由筛选器名称识别,后面跟着一个等号,后面是用逗号分隔的参数值。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue
```

上一个示例用两个参数定义了`Cookie`路由谓词工厂,cookie 名`mycookie`和要匹配`mycookievalue`的值。

### [](#fully-expanded-arguments)[4.2.完全展开的论证](#fully-expanded-arguments) ###

完全展开的参数看起来更像是带有名称/值对的标准 YAML 配置。通常,会有`name`键和`args`键。`args`键是用于配置谓词或筛选器的键值对的映射。

应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue
```

这是上面显示的`Cookie`谓词的快捷配置的完整配置。

[](#gateway-request-predicates-factories)[5.路线谓词工厂](#gateway-request-predicates-factories)
----------

Spring 云网关将路由匹配为 Spring WebFlux`HandlerMapping`基础设施的一部分。 Spring 云网关包括许多内置的路由谓词工厂。所有这些谓词在 HTTP 请求的不同属性上匹配。你可以将多个路由谓词工厂与逻辑`and`语句组合在一起。

### [](#the-after-route-predicate-factory)[5.1.后路由谓词工厂](#the-after-route-predicate-factory) ###

`After`路由谓词工厂接受一个参数,一个`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的 DateTime 之后发生的请求。下面的示例配置一个 after 路由谓词:

示例 1.应用程序.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何请求后提出的 JAN20,2017 年 17:42 山区时间(丹佛)。

### [](#the-before-route-predicate-factory)[5.2.前路由谓词工厂](#the-before-route-predicate-factory) ###

`Before`路由谓词工厂接受一个参数,a`datetime`(这是一个 Java`ZonedDateTime`)。此谓词匹配在指定的`datetime`之前发生的请求。下面的示例配置一个 before 路由谓词:

示例 2.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
```

这条路线符合任何在 JAN20,2017 年 17:42 山区时间(丹佛)之前提出的请求。

### [](#the-between-route-predicate-factory)[5.3.路由谓词之间的工厂](#the-between-route-predicate-factory) ###

`Between`路由谓词工厂接受两个参数,`datetime1`和`datetime2`,它们是 Java`ZonedDateTime`对象。此谓词匹配发生在`datetime1`之后和`datetime2`之前的请求。`datetime2`参数必须位于`datetime1`之后。下面的示例配置了一个 between 路由谓词:

示例 3.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
```

这条路线符合在 JAN20,2017 年 17:42 山区时间(丹佛)之后和 JAN21,2017 年 17:42 山区时间(丹佛)之前提出的任何请求。这对于维护窗口可能是有用的。

### [](#the-cookie-route-predicate-factory)[5.4.cookie 路由谓词工厂](#the-cookie-route-predicate-factory) ###

`Cookie`路由谓词工厂接受两个参数,cookie`name`和`regexp`(这是一个 Java 正则表达式)。此谓词匹配具有给定名称且其值与正则表达式匹配的 cookie。下面的示例配置了一个 Cookie 路由谓词工厂:

示例 4.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p
```

此路由匹配具有名为`chocolate`的 cookie 的请求,其值与`ch.p`正则表达式匹配。

### [](#the-header-route-predicate-factory)[5.5.头路由谓词工厂](#the-header-route-predicate-factory) ###

`Header`路由谓词工厂接受两个参数,`header`和`regexp`(这是一个 Java 正则表达式)。此谓词与具有给定名称的头匹配,其值与正则表达式匹配。下面的示例配置头路由谓词:

示例 5.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
```

如果请求有一个名为`X-Request-Id`的头,其值与`\d+`正则表达式匹配(即它有一个或多个数字的值),则此路由匹配。

### [](#the-host-route-predicate-factory)[5.6.主机路由谓词工厂](#the-host-route-predicate-factory) ###

`Host`路由谓词工厂接受一个参数:主机名列表`patterns`。该模式是一种 Ant 样式的模式,以`.`作为分隔符。此谓词匹配与模式匹配的`Host`头。下面的示例配置了一个主机路由谓词:

示例 6.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org
```

URI 模板变量(如`{sub}.myhost.org`)也受到支持。

如果请求具有`Host`头,其值为`www.somehost.org`或`beta.somehost.org`或`www.anotherhost.org`,则此路由匹配。

这个谓词提取 URI 模板变量(例如`sub`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

### [](#the-method-route-predicate-factory)[5.7.路由谓词工厂的方法](#the-method-route-predicate-factory) ###

`Method`路由谓词工厂接受一个`methods`参数,该参数是一个或多个参数:要匹配的 HTTP 方法。下面的示例配置了一个方法路由谓词:

示例 7.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST
```

如果请求方法是`GET`或`POST`,则此路由匹配。

### [](#the-path-route-predicate-factory)[5.8.路径谓词工厂](#the-path-route-predicate-factory) ###

`Path`路由谓词工厂接受两个参数: Spring `PathMatcher``patterns`的列表和一个名为`matchTrailingSlash`的可选标志(默认为`true`)。下面的示例配置了一个路径路由谓词:

示例 8.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}
```

如果请求路径是:例如:`/red/1`或`/red/1/`或`/red/blue`或`/blue/green`,则此路由匹配。

如果`matchTrailingSlash`被设置为`false`,那么请求路径`/red/1/`将不会被匹配。

这个谓词提取 URI 模板变量(例如`segment`,在前面的示例中定义)作为名称和值的映射,并将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`中定义一个键。这些值可由[“GatewayFilter”工厂](#gateway-route-filters)使用

一种实用方法(称为`get`)可以使访问这些变量变得更容易。下面的示例展示了如何使用`get`方法:

```
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");
```

### [](#the-query-route-predicate-factory)[5.9.查询路由谓词工厂](#the-query-route-predicate-factory) ###

`Query`路由谓词工厂接受两个参数:一个必需的`param`和一个可选的`regexp`(这是一个 Java 正则表达式)。下面的示例配置一个查询路由谓词:

示例 9.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green
```

如果请求包含`green`查询参数,则前面的路由匹配。

application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.
```

如果请求包含一个`red`查询参数,其值与`gree.`regexp 匹配,则前面的路由匹配,因此`green`和`greet`将匹配。

### [](#the-remoteaddr-route-predicate-factory)[5.10.RemoteAddr 路由谓词工厂](#the-remoteaddr-route-predicate-factory) ###

`RemoteAddr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。以下示例配置了一个 RemoteAddr 路由谓词:

示例 10.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24
```

如果请求的远程地址是`192.168.1.10`,则此路由匹配。

#### [](#modifying-the-way-remote-addresses-are-resolved)[5.10.1.修改远程地址的解析方式](#modifying-the-way-remote-addresses-are-resolved) ####

默认情况下,RemoteAddr 路由谓词工厂使用来自传入请求的远程地址。如果 Spring 云网关位于代理层的后面,这可能与实际的客户端 IP 地址不匹配。

你可以通过设置自定义`RemoteAddressResolver`来定制远程地址的解析方式。 Spring 云网关带有一个基于[X-forward-for 标头](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For),`XForwardedRemoteAddressResolver`的非默认远程地址解析器。

`XForwardedRemoteAddressResolver`有两个静态构造函数方法,它们采用不同的方法实现安全性:

* `XForwardedRemoteAddressResolver::trustAll`返回一个`RemoteAddressResolver`,它总是使用在`X-Forwarded-For`头中找到的第一个 IP 地址。这种方法容易受到欺骗,因为恶意客户端可能会为`X-Forwarded-For`设置初始值,该初始值将被解析器接受。

* `XForwardedRemoteAddressResolver::maxTrustedIndex`获取一个索引,该索引与在 Spring 云网关前运行的受信任基础设施的数量相关。 Spring 如果云网关例如只能通过 HAProxy 访问,那么应该使用 1 的值。如果在访问 Spring 云网关之前需要两次跳可信的基础设施,那么应该使用 2 的值。

考虑以下标头值:

```
X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3
```

以下`maxTrustedIndex`值产生以下远程地址:

|   `maxTrustedIndex`    |结果|
|------------------------|-----------------------------------------------------------|
|[`Integer.MIN_VALUE`,0] |(无效,`IllegalArgumentException`在初始化期间)|
|           1            |                          0.0.0.3                          |
|           2            |                          0.0.0.2                          |
|           3            |                          0.0.0.1                          |
|[4, `Integer.MAX_VALUE`]|                          0.0.0.1                          |

下面的示例展示了如何使用 Java 实现相同的配置:

例 11。gatewayconfig.java

```
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)
```

### [](#the-weight-route-predicate-factory)[5.11.权重路径谓词工厂](#the-weight-route-predicate-factory) ###

`Weight`路由谓词工厂接受两个参数:`group`和`weight`(一个 INT)。权重是按组计算的。下面的示例配置了权重路由谓词:

示例 12.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
```

此路线将把 80% 的流量转发给[weighthigh.org](https://weighthigh.org),并将 20% 的流量转发给[weighlow.org](https://weighlow.org)。

### [](#the-xforwarded-remote-addr-route-predicate-factory)[5.12.XForwarded 远程 addr 路由谓词工厂](#the-xforwarded-remote-addr-route-predicate-factory) ###

`XForwarded Remote Addr`路由谓词工厂接受一个`sources`的列表(最小大小为 1),这些字符串是 CIDR 表示法(IPv4 或 IPv6)字符串,例如`192.168.0.1/16`(其中`192.168.0.1`是一个 IP 地址,`16`是一个子网掩码)。

此路由谓词允许基于`X-Forwarded-For`HTTP 报头对请求进行过滤。

这可以用于反向代理,例如负载均衡器或 Web 应用程序防火墙,在这些代理中,只有当请求来自由这些反向代理使用的受信任的 IP 地址列表时,才允许请求。

下面的示例配置了一个 XForWardeDremoteaddr 路由谓词:

示例 13.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: xforwarded_remoteaddr_route
        uri: https://example.org
        predicates:
        - XForwardedRemoteAddr=192.168.1.1/24
```

如果`X-Forwarded-For`标头包含`192.168.1.10`,则此路由匹配。

[](#gatewayfilter-factories)[6. `GatewayFilter` Factories](#gatewayfilter-factories)
----------

路由过滤器允许以某种方式修改传入 HTTP 请求或传出 HTTP 响应。路由过滤器的作用域是特定的路由。 Spring 云网关包括许多内置的网关过滤工厂。

|   |有关如何使用以下任何过滤器的更详细示例,请查看[unit tests](https://github.com/spring-cloud/spring-cloud-gateway/tree/master/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/filter/factory)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-addrequestheader-gatewayfilter-factory)[6.1. The `AddRequestHeader` `GatewayFilter` Factory](#the-addrequestheader-gatewayfilter-factory) ###

`AddRequestHeader``GatewayFilter`工厂接受一个`name`和`value`参数。以下示例配置`AddRequestHeader``GatewayFilter`:

示例 14.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue
```

对于所有匹配的请求,此清单将`X-Request-red:blue`头添加到下游请求的头。

`AddRequestHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestHeader``GatewayFilter`:

示例 15.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}
```

### [](#the-addrequestparameter-gatewayfilter-factory)[6.2. The `AddRequestParameter` `GatewayFilter` Factory](#the-addrequestparameter-gatewayfilter-factory) ###

`AddRequestParameter``GatewayFilter`工厂接受`name`和`value`参数。下面的示例配置`AddRequestParameter``GatewayFilter`:

示例 16.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue
```

这将为所有匹配的请求将`red=blue`添加到下游请求的查询字符串中。

`AddRequestParameter`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`AddRequestParameter``GatewayFilter`:

示例 17.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}
```

### [](#the-addresponseheader-gatewayfilter-factory)[6.3. The `AddResponseHeader` `GatewayFilter` Factory](#the-addresponseheader-gatewayfilter-factory) ###

`AddResponseHeader``GatewayFilter`工厂接受一个`name`和`value`参数。以下示例配置`AddResponseHeader``GatewayFilter`:

示例 18.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue
```

这将为所有匹配的请求向下游响应的头添加`X-Response-Red:Blue`头。

`AddResponseHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置了使用变量的`AddResponseHeader``GatewayFilter`:

示例 19.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}
```

### [](#the-deduperesponseheader-gatewayfilter-factory)[6.4. The `DedupeResponseHeader` `GatewayFilter` Factory](#the-deduperesponseheader-gatewayfilter-factory) ###

DedupeResponseHeader 网关过滤器工厂接受一个`name`参数和一个可选的`strategy`参数。`name`可以包含一个以空格分隔的标题名称列表。以下示例配置`DedupeResponseHeader``GatewayFilter`:

示例 20.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
```

在网关 CORS 逻辑和下游逻辑都添加响应头的情况下,这将删除重复的`Access-Control-Allow-Credentials`和`Access-Control-Allow-Origin`响应头的值。

`DedupeResponseHeader`过滤器还接受一个可选的`strategy`参数。接受的值是`RETAIN_FIRST`(默认)、`RETAIN_LAST`和`RETAIN_UNIQUE`。

### [](#spring-cloud-circuitbreaker-filter-factory)[6.5. Spring Cloud CircuitBreaker GatewayFilter Factory](#spring-cloud-circuitbreaker-filter-factory) ###

Spring 云断路器网关过滤器工厂使用 Spring 云断路器 API 将网关路由封装在断路器中。 Spring Cloud Circuitbreaker 支持可与 Spring Cloud Gateway 一起使用的多个库。 Spring 云支持开箱即用的弹性 4J。

要启用 Spring 云电路断路器过滤器,你需要在 Classpath 上放置`spring-cloud-starter-circuitbreaker-reactor-resilience4j`。下面的示例配置 Spring 云电路断路器`GatewayFilter`:

示例 21.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker
```

要配置断路器,请参阅你正在使用的底层断路器实现的配置。

* [复原力 4J 文档](https://cloud.spring.io/spring-cloud-circuitbreaker/reference/html/spring-cloud-circuitbreaker.html)

Spring 云电路断路器过滤器还可以接受可选的`fallbackUri`参数。目前,只支持`forward:`模式 URI。如果回退被调用,请求将被转发到与 URI 匹配的控制器。下面的示例配置了这种回退:

示例 22.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
```

下面的列表在 Java 中做了相同的事情:

例 23。application.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

当调用断路器回退时,此示例转发到`/inCaseofFailureUseThis`URI。请注意,此示例还演示了(可选的) Spring 云负载平衡器负载平衡(由目标 URI 上的`lb`前缀定义)。

主要的场景是使用`fallbackUri`在网关应用程序中定义内部控制器或处理程序。但是,你也可以将请求重新路由到外部应用程序中的控制器或处理程序,如下所示:

示例 24.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
```

在此示例中,网关应用程序中没有`fallback`端点或处理程序。然而,在另一个应用程序中有一个,注册在`[localhost:9994](http://localhost:9994)`下。

在请求被转发到 Fallback 的情况下, Spring Cloud Circuitbreaker 网关过滤器还提供了导致它的`Throwable`。它被添加到`ServerWebExchange`中,作为`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR`属性,该属性可以在处理网关应用程序内的回退时使用。

对于外部控制器/处理程序场景,可以添加带有异常详细信息的头。你可以在[FallbackHeaders GatewayFilter 工厂部分](#fallback-headers)中找到有关这样做的更多信息。

#### [](#circuit-breaker-status-codes)[6.5.1.按状态码切断断路器](#circuit-breaker-status-codes) ####

在某些情况下,你可能希望基于从其封装的路由返回的状态码来跳闸断路器。断路器配置对象获取一系列状态代码,如果返回这些代码,将导致断路器跳闸。在设置要跳闸的状态码时,可以使用带有状态码值的整数,也可以使用`HttpStatus`枚举的字符串表示。

示例 25.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"
```

例 26。应用程序.java

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis").addStatusCode("INTERNAL_SERVER_ERROR"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}
```

### [](#fallback-headers)[6.6. The `FallbackHeaders` `GatewayFilter` Factory](#fallback-headers) ###

`FallbackHeaders`工厂允许你在转发到外部应用程序中的`fallbackUri`的请求的标题中添加 Spring Cloud Circuitbreaker 执行异常详细信息,如下所示:

示例 27.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header
```

在本例中,在运行断路器时发生执行异常后,请求被转发到在`localhost:9994`上运行的应用程序中的`fallback`端点或处理程序。带有异常类型、消息和(如果可用的话)根原因异常类型和消息的头将由`FallbackHeaders`过滤器添加到该请求中。

你可以通过设置以下参数的值(以它们的默认值显示)来覆盖配置中的头的名称:

* `executionExceptionTypeHeaderName`(`“execution-exception-type”`)

* `executionExceptionMessageHeaderName`(`“execution-exception-message”`)

* `rootCauseExceptionTypeHeaderName`(`“root-cause-exception-type”`)

* `rootCauseExceptionMessageHeaderName`(`“root-cause-exception-message”`)

有关断路器和网关的更多信息,请参见[Spring Cloud CircuitBreaker Factory section](#spring-cloud-circuitbreaker-filter-factory)。

### [](#the-maprequestheader-gatewayfilter-factory)[6.7. The `MapRequestHeader` `GatewayFilter` Factory](#the-maprequestheader-gatewayfilter-factory) ###

`MapRequestHeader``GatewayFilter`工厂接受`fromHeader`和`toHeader`参数。它将创建一个新的命名头,并从传入的 HTTP 请求中从现有的命名头中提取该值。如果输入标头不存在,则过滤器不会产生任何影响。如果新的命名标头已经存在,那么它的值将被新的值扩充。以下示例配置`MapRequestHeader`:

示例 28.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red
```

这会将`X-Request-Red:<values>`头添加到下游请求,并从传入的 HTTP 请求的`Blue`头更新其值。

### [](#the-prefixpath-gatewayfilter-factory)[6.8. The `PrefixPath` `GatewayFilter` Factory](#the-prefixpath-gatewayfilter-factory) ###

`PrefixPath``GatewayFilter`工厂接受一个`prefix`参数。下面的示例配置`PrefixPath``GatewayFilter`:

示例 29.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath
```

这将在所有匹配请求的路径前缀`/mypath`。因此,对`/hello`的请求将被发送到`/mypath/hello`。

### [](#the-preservehostheader-gatewayfilter-factory)[6.9. The `PreserveHostHeader` `GatewayFilter` Factory](#the-preservehostheader-gatewayfilter-factory) ###

`PreserveHostHeader``GatewayFilter`工厂没有参数。此筛选器设置一个请求属性,由路由筛选器检查该属性,以确定是否应发送原始的主机头,而不是由 HTTP 客户机确定的主机头。以下示例配置`PreserveHostHeader``GatewayFilter`:

示例 30.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader
```

### [](#the-requestratelimiter-gatewayfilter-factory)[6.10. The `RequestRateLimiter` `GatewayFilter` Factory](#the-requestratelimiter-gatewayfilter-factory) ###

`RequestRateLimiter``GatewayFilter`工厂使用`RateLimiter`实现来确定是否允许当前请求继续执行。如果不是,则返回`HTTP 429 - Too Many Requests`(默认情况下)的状态。

这个过滤器接受一个可选的`keyResolver`参数和特定于速率限制器的参数(将在本节后面描述)。

`keyResolver`是实现`KeyResolver`接口的 Bean。在配置中,使用 spel 按名称引用 Bean。`#{@mykeyresolver}` 是引用名为`myKeyResolver`的 Bean 的 spel 表达式。下面的清单显示了`KeyResolver`接口:

例 31。keyresolver.java

```
public interface KeyResolver {
    Mono<String> resolve(ServerWebExchange exchange);
}
```

`KeyResolver`接口让可插入策略派生限制请求的键。在未来的里程碑版本中,将会有一些`KeyResolver`实现。

`KeyResolver`的默认实现是`PrincipalNameKeyResolver`,它从`ServerWebExchange`检索`Principal`并调用`Principal.getName()`。

默认情况下,如果`KeyResolver`没有找到密钥,请求将被拒绝。你可以通过设置`spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key`(`true’或`false`)和`spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code`属性来调整此行为。

|   |`RequestRateLimiter`不能使用“shortcut”符号进行配置。下面的示例是*无效*:<br/><br/>示例 32.application.properties<br/><br/>```<br/># 无效的快捷方式配置<br/> Spring.cloud.gateway.routes[0].filters[0]=requestrateLimiter=2,2,#{@userkeyresolever=“426”/>```|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#the-redis-ratelimiter)[6.10.1. The Redis `RateLimiter`](#the-redis-ratelimiter) ####

Redis 实现基于在[Stripe](https://stripe.com/blog/rate-limiters)上完成的工作。它需要使用`spring-boot-starter-data-redis-reactive` Spring 引导启动器。

使用的算法是[令牌桶算法](https://en.wikipedia.org/wiki/Token_bucket)

`redis-rate-limiter.replenishRate`属性是你希望用户在不删除任何请求的情况下每秒可以执行多少个请求。这是令牌桶被填满的速率。

`redis-rate-limiter.burstCapacity`属性是用户在一秒钟内被允许执行的最大请求数。这是令牌桶可以容纳的令牌数量。将此值设置为零将阻止所有请求。

`redis-rate-limiter.requestedTokens`属性是一个请求需要多少令牌。这是每个请求从 bucket 中获取的令牌的数量,默认为`1`

通过在`replenishRate``burstCapacity`中设置相同的值,可以实现稳定的速率。可以通过将`burstCapacity`设置为高于`replenishRate`来允许临时突发。在这种情况下,速率限制器需要允许在两次突发之间有一段时间(根据`replenishRate`),因为连续两次突发将导致丢弃请求(`HTTP429-太多请求’)。下面的清单配置了`redis-rate-limiter`:

速率限制`1 request/s`通过将`replenishRate`设置为所需的请求数,`requestedTokens`设置为秒内的时间跨度,`burstCapacity`设置为`replenishRate`和`requestedTokens`的乘积,例如,设置`replenishRate=1`,`requestedTokens=60`和`burstCapacity=60`将导致`1 request/min`的限制。

示例 33.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1
```

下面的示例在 Java 中配置一个 keyresolver:

例 34。config.java

```
@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
```

这定义了每个用户 10 个的请求速率限制。允许突发 20 个请求,但在接下来的一秒钟内,只有 10 个请求可用。`KeyResolver`是一个获得`user`请求参数的简单参数(请注意,这不推荐用于生产)。

还可以将速率限制器定义为实现`RateLimiter`接口的 Bean。在配置中,你可以使用 spel 按名称引用 Bean。`#{@myratelimiter}` 是一个 spel 表达式,它引用名为`myRateLimiter`的 Bean。下面的清单定义了一个速率限制器,该限制器使用上一个清单中定义的`KeyResolver`:

示例 35.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"
```

### [](#the-redirectto-gatewayfilter-factory)[6.11. The `RedirectTo` `GatewayFilter` Factory](#the-redirectto-gatewayfilter-factory) ###

`RedirectTo``GatewayFilter`工厂接受两个参数,`status`和`url`。`status`参数应该是 300 系列重定向 HTTP 代码,例如 301。`url`参数应该是一个有效的 URL。这是`Location`标头的值。对于相对重定向,应该使用`uri: no://op`作为路由定义的 URI。下面的列表配置了`RedirectTo``GatewayFilter`:

示例 36.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org
```

这将发送带有`Location:https://acme.org`头的状态 302 来执行重定向。

### [](#the-removerequestheader-gatewayfilter-factory)[6.12. The `RemoveRequestHeader` GatewayFilter Factory](#the-removerequestheader-gatewayfilter-factory) ###

`RemoveRequestHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveRequestHeader``GatewayFilter`:

示例 37.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo
```

这将在向下游发送`X-Request-Foo`头之前删除它。

### [](#removeresponseheader-gatewayfilter-factory)[6.13. `RemoveResponseHeader` `GatewayFilter` Factory](#removeresponseheader-gatewayfilter-factory) ###

`RemoveResponseHeader``GatewayFilter`工厂接受一个`name`参数。它是要删除的标头的名称。下面的列表配置了`RemoveResponseHeader``GatewayFilter`:

示例 38.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo
```

这将在响应返回到网关客户机之前从响应中删除`X-Response-Foo`头。

要删除任何类型的敏感报头,你应该为你可能想要删除的任何路由配置此筛选器。此外,你可以使用`spring.cloud.gateway.default-filters`配置该过滤器一次,并将其应用于所有路由。

### [](#the-removerequestparameter-gatewayfilter-factory)[6.14. The `RemoveRequestParameter` `GatewayFilter` Factory](#the-removerequestparameter-gatewayfilter-factory) ###

`RemoveRequestParameter``GatewayFilter`工厂接受一个`name`参数。它是要删除的查询参数的名称。下面的示例配置`RemoveRequestParameter``GatewayFilter`:

示例 39.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red
```

这将在向下游发送`red`参数之前删除该参数。

### [](#the-rewritepath-gatewayfilter-factory)[6.15. The `RewritePath` `GatewayFilter` Factory](#the-rewritepath-gatewayfilter-factory) ###

`RewritePath``GatewayFilter`工厂接受一个路径`regexp`参数和一个`replacement`参数。这使用 Java 正则表达式以灵活的方式重写请求路径。下面的列表配置了`RewritePath``GatewayFilter`:

示例 40.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/?(?<segment>.*), /$\{segment}
```

应该替换为`$\`

### [](#rewritelocationresponseheader-gatewayfilter-factory)[6.16. `RewriteLocationResponseHeader` `GatewayFilter` Factory](#rewritelocationresponseheader-gatewayfilter-factory) ###

`RewriteLocationResponseHeader``GatewayFilter`工厂修改`Location`响应头的值,通常是为了去掉后台特定的细节。它需要`stripVersionMode``locationHeaderName``hostValue``protocolsRegex`参数。下面的列表配置了`RewriteLocationResponseHeader``GatewayFilter`:

示例 41.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewritelocationresponseheader_route
        uri: http://example.org
        filters:
        - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
```

例如,对于`POST [api.example.com/some/object/name](https://api.example.com/some/object/name)`的请求,`Location`的响应头值`[object-service.prod.example.net/v2/some/object/id](https://object-service.prod.example.net/v2/some/object/id)`被重写为`[api.example.com/some/object/id](https://api.example.com/some/object/id)`

`stripVersionMode`参数有以下可能的值:`NEVER_STRIP``AS_IN_REQUEST`(默认),和`ALWAYS_STRIP`

* `NEVER_STRIP`:即使原始请求路径不包含版本,也不会剥离版本。

* `AS_IN_REQUEST`只有当原始请求路径不包含版本时,才会剥离版本。

* `ALWAYS_STRIP`版本总是被剥离,即使原始请求路径包含版本。

如果提供了`hostValue`参数,则用于替换响应`host:port`头的`host:port`部分。如果没有提供,则使用`Host`请求头的值。

参数`protocolsRegex`必须是一个有效的 regex`String`,协议名称与该 regex 匹配。如果不匹配,过滤器就不会做任何事情。默认值为`http|https|ftp|ftps`

### [](#the-rewriteresponseheader-gatewayfilter-factory)[6.17. The `RewriteResponseHeader` `GatewayFilter` Factory](#the-rewriteresponseheader-gatewayfilter-factory) ###

`RewriteResponseHeader``GatewayFilter`工厂接受`name``regexp``replacement`参数。它使用 Java 正则表达式以一种灵活的方式重写响应头值。下面的示例配置`RewriteResponseHeader``GatewayFilter`:

示例 42.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        - RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***
```



### [](#the-savesession-gatewayfilter-factory)[6.18. The `SaveSession` `GatewayFilter` Factory](#the-savesession-gatewayfilter-factory) ###

`SaveSession``GatewayFilter`工厂强制执行`WebSession::save`操作*在此之前*向下游转发呼叫。这在使用带有惰性数据存储的[Spring Session](https://projects.spring.io/spring-session/)之类的东西时特别有用,并且需要确保在进行转发调用之前保存了会话状态。以下示例配置`SaveSession``GatewayFilter`:

示例 43.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: save_session
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        - SaveSession
```

如果你将[Spring Security](https://projects.spring.io/spring-security/)与 Spring 会话集成,并希望确保已将安全细节转发到远程进程,这是非常关键的。

### [](#the-secureheaders-gatewayfilter-factory)[6.19. The `SecureHeaders` `GatewayFilter` Factory](#the-secureheaders-gatewayfilter-factory) ###

`SecureHeaders``GatewayFilter`工厂根据[this blog post](https://blog.appcanary.com/2017/http-security-headers.html)中提出的建议,向响应添加了许多标题。

添加了以下标题(以其默认值显示):

* `X-Xss-Protection:1 (mode=block`)

* `Strict-Transport-Security (max-age=631138519`)

* `X-Frame-Options (DENY)`

* `X-Content-Type-Options (nosniff)`

* `Referrer-Policy (no-referrer)`

* `Content-Security-Policy (default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline)'`

* `X-Download-Options (noopen)`

* `X-Permitted-Cross-Domain-Policies (none)`

要更改默认值,请在`spring.cloud.gateway.filter.secure-headers`名称空间中设置适当的属性。以下属性可供选择:

* `xss-protection-header`

* `strict-transport-security`

* `x-frame-options`

* `x-content-type-options`

* `referrer-policy`

* `content-security-policy`

* `x-download-options`

* `x-permitted-cross-domain-policies`

要禁用默认值,请使用逗号分隔的值设置`spring.cloud.gateway.filter.secure-headers.disable`属性。下面的示例展示了如何做到这一点:

```
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
```

|   |需要使用安全报头的小写字母全名来禁用它。|
|---|-----------------------------------------------------------------------------|

### [](#the-setpath-gatewayfilter-factory)[6.20. The `SetPath` `GatewayFilter` Factory](#the-setpath-gatewayfilter-factory) ###

`SetPath``GatewayFilter`工厂接受一个路径`template`参数。它提供了一种简单的方法,通过允许模板化的路径段来操作请求路径。这使用了 Spring Framework 中的 URI 模板。允许多个匹配段。以下示例配置`SetPath``GatewayFilter`:

示例 44.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - SetPath=/{segment}
```

对于`/red/blue`的请求路径,在发出下游请求之前,将路径设置为`/blue`

### [](#the-setrequestheader-gatewayfilter-factory)[6.21. The `SetRequestHeader` `GatewayFilter` Factory](#the-setrequestheader-gatewayfilter-factory) ###

`SetRequestHeader``GatewayFilter`工厂接受`name``value`参数。下面的列表配置了`SetRequestHeader``GatewayFilter`:

示例 45.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        filters:
        - SetRequestHeader=X-Request-Red, Blue
```

这个`GatewayFilter`用给定的名称替换(而不是添加)所有的头。因此,如果下游服务器用`X-Request-Red:1234`响应,这将被替换为`X-Request-Red:Blue`,这是下游服务将接收的内容。

`SetRequestHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并在运行时展开。下面的示例配置使用变量的`SetRequestHeader``GatewayFilter`:

示例 46.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetRequestHeader=foo, bar-{segment}
```

### [](#the-setresponseheader-gatewayfilter-factory)[6.22. The `SetResponseHeader` `GatewayFilter` Factory](#the-setresponseheader-gatewayfilter-factory) ###

`SetResponseHeader``GatewayFilter`工厂接受`name``value`参数。下面的列表配置了`SetResponseHeader``GatewayFilter`:

示例 47.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        filters:
        - SetResponseHeader=X-Response-Red, Blue
```

这个 GatewayFilter 用给定的名称替换(而不是添加)所有的头。因此,如果下游服务器使用`X-Response-Red:1234`进行响应,则将其替换为`X-Response-Red:Blue`,这是网关客户机将接收的内容。

`SetResponseHeader`知道用于匹配路径或主机的 URI 变量。URI 变量可以在值中使用,并将在运行时展开。下面的示例配置使用变量的`SetResponseHeader``GatewayFilter`:

示例 48.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetResponseHeader=foo, bar-{segment}
```

### [](#the-setstatus-gatewayfilter-factory)[6.23. The `SetStatus` `GatewayFilter` Factory](#the-setstatus-gatewayfilter-factory) ###

`SetStatus``GatewayFilter`工厂只接受一个参数,`status`。它必须是有效的 Spring `HttpStatus`。它可以是整数值`404`或枚举的字符串表示:`NOT_FOUND`。下面的列表配置了`SetStatus``GatewayFilter`:

示例 49.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setstatusstring_route
        uri: https://example.org
        filters:
        - SetStatus=UNAUTHORIZED
      - id: setstatusint_route
        uri: https://example.org
        filters:
        - SetStatus=401
```

在这两种情况下,响应的 HTTP 状态都设置为 401。

你可以将`SetStatus``GatewayFilter`配置为从响应中的报头中的代理请求返回原始 HTTP 状态代码。如果配置了以下属性,则会将头添加到响应中:

示例 50.application.yml

```
spring:
  cloud:
    gateway:
      set-status:
        original-status-header-name: original-http-status
```

### [](#the-stripprefix-gatewayfilter-factory)[6.24. The `StripPrefix` `GatewayFilter` Factory](#the-stripprefix-gatewayfilter-factory) ###

`StripPrefix``GatewayFilter`工厂接受一个参数,`parts``parts`参数指示在向下游发送请求之前要从请求中剥离的路径中的部件数量。下面的列表配置了`StripPrefix``GatewayFilter`:

示例 51.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: https://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2
```

当通过网关向`/name/blue/red`发出请求时,向`nameservice`发出的请求看起来像`[nameservice/red](https://nameservice/red)`

### [](#the-retry-gatewayfilter-factory)[6.25. The Retry `GatewayFilter` Factory](#the-retry-gatewayfilter-factory) ###

`Retry``GatewayFilter`工厂支持以下参数:

* `retries`:应该尝试的重试次数。

* `statuses`:应该重试的 HTTP 状态代码,用`org.springframework.http.HttpStatus`表示。

* `methods`:应该重试的 HTTP 方法,用`org.springframework.http.HttpMethod`表示。

* `series`:要重试的一系列状态代码,用`org.springframework.http.HttpStatus.Series`表示。

* `exceptions`:应该重试的抛出的异常列表。

* `backoff`:为重试配置的指数退避。在回退间隔`firstBackoff * (factor ^ n)`之后执行重试,其中`n`是迭代。如果`maxBackoff`已配置,则应用的最大退避限制为`maxBackoff`。如果`basedOnPreviousValue`为真,则按`prevBackoff * factor`计算退避。

如果启用,以下默认值将配置为`Retry`过滤器:

* `retries`:三次

* `series`:5XX 系列

* `methods`:get 方法

* `exceptions`:`IOException``TimeoutException`

* `backoff`:禁用

下面的列表配置了重试`GatewayFilter`:

示例 52.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: retry_test
        uri: http://localhost:8080/flakey
        predicates:
        - Host=*.retry.com
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: BAD_GATEWAY
            methods: GET,POST
            backoff:
              firstBackoff: 10ms
              maxBackoff: 50ms
              factor: 2
              basedOnPreviousValue: false
```

|   |当使用带有`forward:`前缀 URL 的重试筛选器时,目标端点应该仔细地编写,以便在发生错误的情况下,它不会执行任何可能导致将响应发送到客户机并提交的操作,例如,<br/>,如果目标端点是带注释的控制器,则目标控制器方法不应该返回带有错误状态码的`ResponseEntity`,而是应该抛出<br/>,或者发出错误信号(例如,通过`Mono.error(ex)`返回值),重试筛选器可以配置为通过重试来处理该筛选器。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |当在带有主体的任何 HTTP 方法中使用 Retry 过滤器时,主体将被缓存,网关将成为内存约束。主体缓存在由`ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR`定义的请求属性中。对象的类型是`org.springframework.core.io.buffer.DataBuffer`。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

简化的“shortcut”符号可以添加一个`status``method`

以下两个例子是等价的:

示例 53.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: retry_route
        uri: https://example.org
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: INTERNAL_SERVER_ERROR
            methods: GET
            backoff:
              firstBackoff: 10ms
              maxBackoff: 50ms
              factor: 2
              basedOnPreviousValue: false

      - id: retryshortcut_route
        uri: https://example.org
        filters:
        - Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false
```

### [](#the-requestsize-gatewayfilter-factory)[6.26. The `RequestSize` `GatewayFilter` Factory](#the-requestsize-gatewayfilter-factory) ###

当请求大小大于允许的限制时,`RequestSize``GatewayFilter`工厂可以限制请求到达下游服务。过滤器接受`maxSize`参数。`maxSize``DataSize`类型,因此值可以定义为一个数字,后面跟着一个可选的`DataUnit`后缀,例如“KB”或“MB”。对于字节,默认值为“B”。它是以字节为单位定义的请求的允许大小限制。下面的列表配置了`RequestSize``GatewayFilter`:

示例 54.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
        uri: http://localhost:8080/upload
        predicates:
        - Path=/upload
        filters:
        - name: RequestSize
          args:
            maxSize: 5000000
```

当请求由于大小而被拒绝时,`RequestSize`工厂将响应状态设置为`413 Payload Too Large`,并带有一个附加的头`errorMessage`。下面的示例显示了这样的`errorMessage`:

```
errorMessage : Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB
```

|   |如果在路由定义中没有作为筛选参数提供,则默认的请求大小设置为 5MB。|
|---|--------------------------------------------------------------------------------------------------------|

### [](#the-setrequesthostheader-gatewayfilter-factory)[6.27. The `SetRequestHostHeader` `GatewayFilter` Factory](#the-setrequesthostheader-gatewayfilter-factory) ###

在某些情况下,主机标题可能需要被重写。在这种情况下,`SetRequestHostHeader``GatewayFilter`工厂可以用指定的 vaue 替换现有的主机报头。过滤器接受`host`参数。下面的列表配置了`SetRequestHostHeader``GatewayFilter`:

示例 55.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: set_request_host_header_route
        uri: http://localhost:8080/headers
        predicates:
        - Path=/headers
        filters:
        - name: SetRequestHostHeader
          args:
            host: example.org
```

`SetRequestHostHeader``GatewayFilter`工厂将主机报头的值替换为`example.org`

### [](#modify-a-request-body-gatewayfilter-factory)[6.28. Modify a Request Body `GatewayFilter` Factory](#modify-a-request-body-gatewayfilter-factory) ###

你可以使用`ModifyRequestBody`过滤器过滤器来修改请求主体,然后再由网关向下游发送。

|   |这个过滤器只能通过使用 Java DSL 进行配置。|
|---|---------------------------------------------------------|

下面的清单显示了如何修改请求主体`GatewayFilter`:

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
                    (exchange, s) -> return Mono.just(new Hello(s.toUpperCase())))).uri(uri))
        .build();
}

static class Hello {
    String message;

    public Hello() { }

    public Hello(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
```

|   |如果请求没有正文,则将传递`RewriteFilter`。应该返回`Mono.empty()`以分配请求中缺少的主体。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#modify-a-response-body-gatewayfilter-factory)[6.29. Modify a Response Body `GatewayFilter` Factory](#modify-a-response-body-gatewayfilter-factory) ###

你可以使用`ModifyResponseBody`过滤器来修改响应主体,然后再将其发送回客户机。

|   |这个过滤器只能通过使用 Java DSL 进行配置。|
|---|---------------------------------------------------------|

下面的清单显示了如何修改响应主体`GatewayFilter`:

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyResponseBody(String.class, String.class,
                    (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri))
        .build();
}
```

|   |如果响应没有主体,那么`RewriteFilter`将被传递`null`。应该返回`Mono.empty()`,以便在响应中分配一个缺少的主体。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#token-relay-gatewayfilter-factory)[6.30. Token Relay `GatewayFilter` Factory](#token-relay-gatewayfilter-factory) ###

令牌中继是 OAuth2 使用者充当客户端并将传入的令牌转发给传出的资源请求的一种方式。使用者可以是纯客户机(如 SSO 应用程序)或资源服务器。

Spring 云网关可以将 OAuth2 访问令牌转发到其代理的服务的下游。要将此功能添加到 Gateway,你需要添加“TokenRelayGatewayFilterFactory”,如下所示:

app.java

```
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("resource", r -> r.path("/resource")
                    .filters(f -> f.tokenRelay())
                    .uri("http://localhost:9000"))
            .build();
}
```

或者这个

应用程序.YAML

```
spring:
  cloud:
    gateway:
      routes:
      - id: resource
        uri: http://localhost:9000
        predicates:
        - Path=/resource
        filters:
        - TokenRelay=
```

并且它将(除了登录用户并获取令牌之外)向下游传递身份验证令牌到服务(在这种情况下是 `/resource`)。

要为 Spring 云网关启用此功能,请添加以下依赖项

* `org.springframework.boot:spring-boot-starter-oauth2-client`

它是如何工作的?{githubmaster}/SRC/main/java/org/springframework/cloud/gateway/security/tokenrelaygatewayfilterfactory.java[filter]从当前经过身份验证的用户中提取一个访问令牌,并将其放在下游请求的请求头中。

有关完整的工作示例,请参见[this project](https://github.com/spring-cloud-samples/sample-gateway-oauth2login)

|   |只有设置了适当的`spring.security.oauth2.client.*`属性才会创建`TokenRelayGatewayFilterFactory` Bean,这将触发创建`ReactiveClientRegistrationRepository` Bean。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |`TokenRelayGatewayFilterFactory`使用的`ReactiveOAuth2AuthorizedClientService`的默认实现使用内存中的数据存储。如果需要更健壮的解决方案,则需要提供自己的实现`ReactiveOAuth2AuthorizedClientService`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-cacherequestbody-gatewayfilter-factory)[6.31. The `CacheRequestBody` `GatewayFilter` Factory](#the-cacherequestbody-gatewayfilter-factory) ###

由于请求体流只能被读取一次,所以需要对请求体流进行缓存。你可以使用`CacheRequestBody`过滤器来缓存请求主体,然后再将其发送到下游,并从 exchagne 属性获取主体。

下面的清单显示了如何缓存请求主体`GatewayFilter`:

```
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("cache_request_body_route", r -> r.path("/downstream/**")
            .filters(f -> f.prefixPath("/httpbin")
                .cacheRequestBody(String.class).uri(uri))
        .build();
}
```

示例 56.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: cache_request_body_route
        uri: lb://downstream
        predicates:
        - Path=/downstream/**
        filters:
        - name: CacheRequestBody
          args:
            bodyClass: java.lang.String
```

`CacheRequestBody`将提取请求主体并将其转换为主体类(如`java.lang.String`,在前面的示例中定义)。然后将其放置在`ServerWebExchange.getAttributes()`中,并在`ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR`中定义一个键。

|   |此过滤器仅适用于 HTTP 请求(包括 HTTPS)。|
|---|-----------------------------------------------------------|

### [](#default-filters)[6.32.默认过滤器](#default-filters) ###

要添加筛选器并将其应用到所有路由,你可以使用`spring.cloud.gateway.default-filters`。此属性接受一个过滤器列表。下面的清单定义了一组默认筛选器:

示例 57.application.yml

```
spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Red, Default-Blue
      - PrefixPath=/httpbin
```

[](#global-filters)[7.全局过滤器](#global-filters)
----------

`GlobalFilter`接口具有与`GatewayFilter`相同的签名。这些是有条件地应用于所有路由的特殊过滤器。

|   |该接口及其使用情况可能会在未来的里程碑版本中发生更改。|
|---|--------------------------------------------------------------------------------|

### [](#gateway-combined-global-filter-and-gatewayfilter-ordering)[7.1. Combined Global Filter and `GatewayFilter` Ordering](#gateway-combined-global-filter-and-gatewayfilter-ordering) ###

当请求与路由匹配时,过滤 Web 处理程序将`GlobalFilter`的所有实例和`GatewayFilter`的所有特定于路由的实例添加到筛选链中。这个组合的过滤器链通过`org.springframework.core.Ordered`接口进行排序,你可以通过实现`getOrder()`方法来设置该接口。

Spring 由于云网关对用于过滤器逻辑执行的“pre”和“post”阶段进行了区分(参见[How it Works](#gateway-how-it-works)),优先级最高的过滤器是“pre”阶段中的第一个,“post”阶段中的最后一个。

下面的清单配置了一个过滤器链:

例 58。示例 configuration.java

```
@Bean
public GlobalFilter customFilter() {
    return new CustomGlobalFilter();
}

public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
```

### [](#forward-routing-filter)[7.2.前向路由滤波器](#forward-routing-filter) ###

`ForwardRoutingFilter`在 exchange 属性`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`中查找 URI。如果 URL 具有`forward`方案(例如`forward:///localendpoint`),则它使用 Spring `DispatcherHandler`来处理请求。请求 URL 的路径部分被转发 URL 中的路径覆盖。未修改的原始 URL 被追加到`ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR`属性中的列表中。

### [](#reactive-loadbalancer-client-filter)[7.3. The `ReactiveLoadBalancerClientFilter`](#reactive-loadbalancer-client-filter) ###

`ReactiveLoadBalancerClientFilter`在名为`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`的 exchange 属性中查找 URI。如果 URL 具有`lb`方案(例如`lb://myservice`),则它使用 Spring cloud`ReactorLoadBalancer`将名称(本例中的 `myservice’)解析为实际的主机和端口,并替换相同属性中的 URI。未修改的原始 URL 被追加到`ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR`属性中的列表中。过滤器还查看`ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR`属性,以查看它是否等于`lb`。如果是这样,也适用同样的规则。下面的列表配置了`ReactiveLoadBalancerClientFilter`:

示例 59.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**
```

|   |默认情况下,当`ReactorLoadBalancer`无法找到服务实例时,将返回一个`503`。<br/>通过设置`spring.cloud.gateway.loadbalancer.use404=true`,你可以将网关配置为返回一个`404`。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |从`ReactiveLoadBalancerClientFilter`返回的`isSecure`值的`ServiceInstance`覆盖了<br/>向网关提出的请求中指定的方案。<br/>例如,如果请求通过`HTTPS`进入网关,但`ServiceInstance`表示它不安全,下游请求是在`HTTP`上提出的。<br/>相反的情况也可以适用。<br/>但是,如果`GATEWAY_SCHEME_PREFIX_ATTR`在网关配置中为该路由指定了前缀,则从路由 URL 中得到的方案将覆盖`ServiceInstance`配置。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |网关支持所有的负载平衡器功能。你可以在[Spring Cloud Commons documentation](https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer)中阅读有关它们的更多信息。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#the-netty-routing-filter)[7.4.Netty 路由过滤器](#the-netty-routing-filter) ###

如果`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`Exchange 属性中的 URL 具有`http`或`https`方案,则运行 Netty 路由过滤器。它使用 netty`HttpClient`发出下游代理请求。将响应放入`ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR`exchange 属性中,以便在以后的筛选器中使用。(还有一个实验性的`WebClientHttpRoutingFilter`,它执行相同的功能,但不需要 netty。

### [](#the-netty-write-response-filter)[7.5.Netty 写响应过滤器](#the-netty-write-response-filter) ###

如果`ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR`exchange 属性中有一个 netty`HttpClientResponse`,则运行`NettyWriteResponseFilter`。它在所有其他过滤器完成并将代理响应写回网关客户机响应之后运行。(还有一个实验性的`WebClientWriteResponseFilter`,它执行相同的功能,但不需要 netty。

### [](#the-routetorequesturl-filter)[7.6. The `RouteToRequestUrl` Filter](#the-routetorequesturl-filter) ###

如果在`ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR`exchange 属性中有一个`Route`对象,则运行`RouteToRequestUrlFilter`。它根据请求 URI 创建一个新的 URI,但使用`Route`对象的 URI 属性进行更新。新的 URI 放在`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`exchange 属性中。

如果 URI 有一个方案前缀,例如`lb:ws://serviceid`,则将从 URI 中剥离`lb`方案,并将其放置在`ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR`中,以便稍后在筛选链中使用。

### [](#the-websocket-routing-filter)[7.7. The Websocket Routing Filter](#the-websocket-routing-filter) ###

如果位于`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`Exchange 属性中的 URL 具有`ws`或`wss`方案,则运行 WebSocket 路由过滤器。它使用 Spring  WebSocket 基础设施向下游转发 WebSocket 请求。

你可以通过在 URI 前加上`lb`来实现 WebSockets 的负载平衡,比如`lb:ws://serviceid`。

|   |如果使用[SockJS](https://github.com/sockjs)作为普通 HTTP 的后备,则应该配置普通 HTTP 路由和 WebSocket 路由。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------|

下面的清单配置了一个 WebSocket 路由过滤器:

示例 60.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      # SockJS route
      - id: websocket_sockjs_route
        uri: http://localhost:3001
        predicates:
        - Path=/websocket/info/**
      # Normal Websocket route
      - id: websocket_route
        uri: ws://localhost:3001
        predicates:
        - Path=/websocket/**
```

### [](#the-gateway-metrics-filter)[7.8.网关指标过滤器](#the-gateway-metrics-filter) ###

要启用网关度量,可以添加 Spring-boot-starter-actuator 作为项目依赖项。然后,默认情况下,只要属性`spring.cloud.gateway.metrics.enabled`未设置为`false`,网关指标过滤器就会运行。该过滤器添加了一个名为`spring.cloud.gateway.requests`的计时器度量,并带有以下标记:

* `routeId`:路径 ID。

* `routeUri`:将 API 路由到的 URI。

* `outcome`:结果,按[HttpStatus.series](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.Series.html)分类。

* `status`:返回给客户机的请求的 HTTP 状态。

* `httpStatusCode`:返回给客户机的请求的 HTTP 状态。

* `httpMethod`:用于请求的 HTTP 方法。

此外,通过属性`spring.cloud.gateway.metrics.tags.path.enabled`(默认情况下,设置为 false),你可以使用标记激活一个额外的度量指标:

* `path`:请求的路径。

然后可以从`/actuator/metrics/spring.cloud.gateway.requests`中获取这些指标,并且可以轻松地与 Prometheus 集成以创建[Grafana](images/gateway-grafana-dashboard.jpeg)[dashboard](gateway-grafana-dashboard.json)。

|   |要启用 Prometheus 端点,请添加`micrometer-registry-prometheus`作为项目依赖项。|
|---|------------------------------------------------------------------------------------------------|

### [](#marking-an-exchange-as-routed)[7.9.将交易所标记为路由](#marking-an-exchange-as-routed) ###

在网关路由了`ServerWebExchange`之后,它通过在 exchange 属性中添加`gatewayAlreadyRouted`将该 exchange 标记为“路由”。一旦一个请求被标记为路由,其他路由过滤器将不会再次路由该请求,基本上跳过该过滤器。有一些方便的方法,你可以使用它来标记一个交换为路由,或者检查一个交换是否已经被路由。

* `ServerWebExchangeUtils.isAlreadyRouted`接受一个`ServerWebExchange`对象,并检查它是否已被“路由”。

* `ServerWebExchangeUtils.setAlreadyRouted`接受一个`ServerWebExchange`对象,并将其标记为“路由”。

[](#httpheadersfilters)[8.HttpHeadersFilters](#httpheadersfilters)
----------

HttpHeadersFilters 在向下游发送请求之前应用于请求,例如在`NettyRoutingFilter`中。

### [](#forwarded-headers-filter)[8.1.转发头过滤器](#forwarded-headers-filter) ###

`Forwarded`headers filter 创建一个`Forwarded`header 以发送到下游服务。它将当前请求的`Host`头、方案和端口添加到任何现有的`Forwarded`头。

### [](#removehopbyhop-headers-filter)[8.2.RemoveHopbyHop Headers 过滤器](#removehopbyhop-headers-filter) ###

`RemoveHopByHop`headers 过滤器从转发的请求中删除 header。被删除的头的默认列表来自[IETF](https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3)。

默认删除的标题是:

* 连接

* 保持活力

* 代理身份验证

* 代理授权

* TE

* 预告片

* 传输编码

* 升级

要更改这一点,请将`spring.cloud.gateway.filter.remove-hop-by-hop.headers`属性设置为要删除的头名称列表。

### [](#xforwarded-headers-filter)[8.3.XForwarded Headers 过滤器](#xforwarded-headers-filter) ###

`XForwarded`headers filter 创建了各种`X-Forwarded-*`headers 以发送到下游服务。它使用`Host`报头、方案、端口和当前请求的路径来创建各种报头。

可以通过以下布尔属性(默认为 true)来控制单个标题的创建:

* `spring.cloud.gateway.x-forwarded.for-enabled`

* `spring.cloud.gateway.x-forwarded.host-enabled`

* `spring.cloud.gateway.x-forwarded.port-enabled`

* `spring.cloud.gateway.x-forwarded.proto-enabled`

* `spring.cloud.gateway.x-forwarded.prefix-enabled`

追加多个头可以由以下布尔属性控制(默认为 true):

* `spring.cloud.gateway.x-forwarded.for-append`

* `spring.cloud.gateway.x-forwarded.host-append`

* `spring.cloud.gateway.x-forwarded.port-append`

* `spring.cloud.gateway.x-forwarded.proto-append`

* `spring.cloud.gateway.x-forwarded.prefix-append`

[](#tls-and-ssl)[9. TLS and SSL](#tls-and-ssl)
----------

网关可以通过遵循通常的 Spring 服务器配置来监听 HTTPS 上的请求。下面的示例展示了如何做到这一点:

示例 61.application.yml

```
server:
  ssl:
    enabled: true
    key-alias: scg
    key-store-password: scg1234
    key-store: classpath:scg-keystore.p12
    key-store-type: PKCS12
```

你可以将网关路由到 HTTP 和 HTTPS 后端。如果要路由到 HTTPS 后端,则可以通过以下配置将网关配置为信任所有下游证书:

示例 62.application.yml

```
spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true
```

使用不安全的信任管理器不适合于生产。对于产品部署,你可以使用一组已知证书来配置网关,它可以通过以下配置来信任这些证书:

示例 63.application.yml

```
spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          trustedX509Certificates:
          - cert1.pem
          - cert2.pem
```

如果 Spring 云网关没有提供受信任的证书,则使用默认的信任存储区(你可以通过设置`javax.net.ssl.trustStore`系统属性来覆盖该存储区)。

### [](#tls-handshake)[9.1.TLS 握手](#tls-handshake) ###

网关维护一个用于路由到后端的客户机池。当通过 HTTPS 进行通信时,客户机发起 TLS 握手。与此握手相关的超时次数很多。你可以配置这些超时可以配置(默认显示)如下:

示例 64.application.yml

```
spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          handshake-timeout-millis: 10000
          close-notify-flush-timeout-millis: 3000
          close-notify-read-timeout-millis: 0
```

[](#configuration)[10.配置](#configuration)
----------

Spring 云网关的配置由`RouteDefinitionLocator`实例的集合驱动。下面的清单显示了`RouteDefinitionLocator`接口的定义:

例 65。RouteDefinitionLocator.java

```
public interface RouteDefinitionLocator {
    Flux<RouteDefinition> getRouteDefinitions();
}
```

默认情况下,`PropertiesRouteDefinitionLocator`通过使用 Spring boot 的`@ConfigurationProperties`机制加载属性。

前面的配置示例都使用了一个快捷方式,它使用位置参数而不是命名参数。以下两个例子是等价的:

示例 66.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: setstatus_route
        uri: https://example.org
        filters:
        - name: SetStatus
          args:
            status: 401
      - id: setstatusshortcut_route
        uri: https://example.org
        filters:
        - SetStatus=401
```

对于网关的某些用法,属性是足够的,但是一些生产用例受益于从外部源(例如数据库)加载配置。未来的里程碑版本将具有基于 Spring 数据存储库的`RouteDefinitionLocator`实现,例如 Redis、MongoDB 和 Cassandra。

### [](#routedefinition-metrics)[10.1.路由定义度量](#routedefinition-metrics) ###

要启用`RouteDefinition`度量,请添加 Spring-boot-starter-actuator 作为项目依赖项。然后,默认情况下,只要将属性`spring.cloud.gateway.metrics.enabled`设置为`true`,度量就可用。将添加一个名为`spring.cloud.gateway.routes.count`的规范度量,其值是`RouteDefinitions`的数量。该指标将从`/actuator/metrics/spring.cloud.gateway.routes.count`开始提供。

[](#route-metadata-configuration)[11.路由元数据配置](#route-metadata-configuration)
----------

你可以通过使用元数据为每个路由配置附加参数,如下所示:

示例 67.application.yml

```
spring:
  cloud:
    gateway:
      routes:
      - id: route_with_metadata
        uri: https://example.org
        metadata:
          optionName: "OptionValue"
          compositeObject:
            name: "value"
          iAmNumber: 1
```

你可以从 Exchange 获取所有元数据属性,如下所示:

```
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
// get all metadata properties
route.getMetadata();
// get a single metadata property
route.getMetadata(someKey);
```

[](#http-timeouts-configuration)[12.HTTP 超时配置](#http-timeouts-configuration)
----------

可以为所有路由配置 HTTP 超时(响应和连接),并为每个特定的路由重写。

### [](#global-timeouts)[12.1.全球超时](#global-timeouts) ###

要配置全局 HTTP 超时:`connect-timeout`必须以毫秒为单位指定。`response-timeout`必须指定为 java.time.duration

全局 HTTP 超时示例

```
spring:
  cloud:
    gateway:
      httpclient:
        connect-timeout: 1000
        response-timeout: 5s
```

### [](#per-route-timeouts)[12.2.每条路线超时](#per-route-timeouts) ###

要配置每个路由超时:`connect-timeout`必须以毫秒为单位指定。`response-timeout`必须以毫秒为单位指定。

通过配置进行每路由 HTTP 超时配置

```
      - id: per_route_timeouts
        uri: https://example.org
        predicates:
          - name: Path
            args:
              pattern: /delay/{timeout}
        metadata:
          response-timeout: 200
          connect-timeout: 200
```

使用 Java DSL 的每路由超时配置

```
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.CONNECT_TIMEOUT_ATTR;
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.RESPONSE_TIMEOUT_ATTR;

      @Bean
      public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder){
         return routeBuilder.routes()
               .route("test1", r -> {
                  return r.host("*.somehost.org").and().path("/somepath")
                        .filters(f -> f.addRequestHeader("header1", "header-value-1"))
                        .uri("http://someuri")
                        .metadata(RESPONSE_TIMEOUT_ATTR, 200)
                        .metadata(CONNECT_TIMEOUT_ATTR, 200);
               })
               .build();
      }
```

带负值的每路由`response-timeout`将禁用全局`response-timeout`值。

```
      - id: per_route_timeouts
        uri: https://example.org
        predicates:
          - name: Path
            args:
              pattern: /delay/{timeout}
        metadata:
          response-timeout: -1
```

### [](#fluent-java-routes-api)[12.3.Fluent Java Routes API](#fluent-java-routes-api) ###

为了允许在 Java 中进行简单的配置,`RouteLocatorBuilder` Bean 包含了一个 Fluent API。下面的清单展示了它的工作原理:

例 68。GatewaySampleApplication.java

```
// static imports from GatewayFilters and RoutePredicates
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
    return builder.routes()
            .route(r -> r.host("**.abc.org").and().path("/image/png")
                .filters(f ->
                        f.addResponseHeader("X-TestHeader", "foobar"))
                .uri("http://httpbin.org:80")
            )
            .route(r -> r.path("/image/webp")
                .filters(f ->
                        f.addResponseHeader("X-AnotherHeader", "baz"))
                .uri("http://httpbin.org:80")
                .metadata("key", "value")
            )
            .route(r -> r.order(-1)
                .host("**.throttle.org").and().path("/get")
                .filters(f -> f.filter(throttle.apply(1,
                        1,
                        10,
                        TimeUnit.SECONDS)))
                .uri("http://httpbin.org:80")
                .metadata("key", "value")
            )
            .build();
}
```

这种样式还允许更多的自定义谓词断言。由`RouteDefinitionLocator`bean 定义的谓词使用逻辑`and`进行组合。通过使用 Fluent Java API,你可以在`Predicate`类上使用`and()`、`or()`和`negate()`运算符。

### [](#the-discoveryclient-route-definition-locator)[12.4. The `DiscoveryClient` Route Definition Locator](#the-discoveryclient-route-definition-locator) ###

你可以将网关配置为基于在`DiscoveryClient`兼容的服务注册中心注册的服务创建路由。

要启用此功能,请设置`spring.cloud.gateway.discovery.locator.enabled=true`,并确保在 Classpath 上启用了`DiscoveryClient`实现(例如 Netflix Eureka、Consul 或 ZooKeeper)。

#### [](#configuring-predicates-and-filters-for-discoveryclient-routes)[12.4.1. Configuring Predicates and Filters For `DiscoveryClient` Routes](#configuring-predicates-and-filters-for-discoveryclient-routes) ####

默认情况下,网关为使用`DiscoveryClient`创建的路由定义一个谓词和过滤器。

缺省谓词是用模式`/serviceId/**`定义的路径谓词,其中`serviceId`是来自`DiscoveryClient`的服务的 ID。

默认的过滤器是一个重写路径过滤器,regex`/serviceId/?(?<remaining>.*)`和替换`/${remaining}`。这将在向下游发送请求之前从路径中剥离服务 ID。

如果要自定义`DiscoveryClient`路由所使用的谓词或筛选器,请设置`spring.cloud.gateway.discovery.locator.predicates[x]`和`spring.cloud.gateway.discovery.locator.filters[y]`。这样做时,如果你想保留该功能,则需要确保包含前面显示的缺省谓词和筛选器。下面的示例显示了这是什么样子的:

示例 69.application.properties

```
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
spring.cloud.gateway.discovery.locator.predicates[1].name: Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'"
spring.cloud.gateway.discovery.locator.filters[0].name: CircuitBreaker
spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId
spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath
spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/?(?<remaining>.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"
```

[](#reactor-netty-access-logs)[13.反应堆网络访问日志](#reactor-netty-access-logs)
----------

要启用反应堆网络访问日志,请设置`-Dreactor.netty.http.server.accessLogEnabled=true`。

|   |它必须是一个 Java 系统属性,而不是 Spring 引导属性。|
|---|--------------------------------------------------------------|

你可以将日志系统配置为具有一个单独的访问日志文件。下面的示例创建了一个注销配置:

示例 70.logback.xml

```
    <appender name="accessLog" class="ch.qos.logback.core.FileAppender">
        <file>access_log.log</file>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="accessLog" />
    </appender>

    <logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
        <appender-ref ref="async"/>
    </logger>
```

[](#cors-configuration)[14.CORS 配置](#cors-configuration)
----------

你可以配置网关来控制 CORS 行为。“全局”CORS 配置是 URL 模式到[Spring Framework `CorsConfiguration`](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html)的映射。以下示例配置 CORS:

示例 71.application.yml

```
spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET
```

在前面的示例中,对于所有 GET 请求的路径,允许从源自`docs.spring.io`的请求发出 CORS 请求。

要为某些网关路由谓词不处理的请求提供相同的 CORS 配置,请将`spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping`属性设置为`true`。当你尝试支持 CORS 的 Preflight 请求,而你的路由谓词不求值到`true`时,这是有用的,因为 HTTP 方法是`options`。

[](#actuator-api)[15.执行机构 API](#actuator-api)
----------

执行器端点`/gateway`允许你监视 Spring 云网关应用程序并与之交互。要实现远程访问,端点必须是应用程序属性中的[enabled](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-enabling-endpoints)和[通过 HTTP 或 JMX 公开](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-exposing-endpoints)。下面的清单展示了如何做到这一点:

示例 72.application.properties

```
management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway
```

### [](#verbose-actuator-format)[15.1.详细执行器格式](#verbose-actuator-format) ###

一种新的、更详细的格式已添加到 Spring Cloud Gateway 中。它为每条路由添加了更多细节,允许你查看与每条路由相关的谓词和筛选器,以及可用的任何配置。以下示例配置`/actuator/gateway/routes`:

```
[
  {
    "predicate": "(Hosts: [**.addrequestheader.org] && Paths: [/headers], match trailing slash: true)",
    "route_id": "add_request_header_test",
    "filters": [
      "[[AddResponseHeader X-Response-Default-Foo = 'Default-Bar'], order = 1]",
      "[[AddRequestHeader X-Request-Foo = 'Bar'], order = 1]",
      "[[PrefixPath prefix = '/httpbin'], order = 2]"
    ],
    "uri": "lb://testservice",
    "order": 0
  }
]
```

默认情况下启用此功能。要禁用它,请设置以下属性:

示例 73.application.properties

```
spring.cloud.gateway.actuator.verbose.enabled=false
```

在将来的版本中,这将默认为`true`。

### [](#retrieving-route-filters)[15.2.检索路由过滤器](#retrieving-route-filters) ###

本节详细介绍了如何检索路由过滤器,包括:

* [Global Filters](#gateway-global-filters)

* [[gateway-route-filters]](#gateway-route-filters)

#### [](#gateway-global-filters)[15.2.1.全局过滤器](#gateway-global-filters) ####

要检索应用于所有路由的[global filters](#global-filters),请对`GET`请求`/actuator/gateway/globalfilters`。由此产生的反应类似于以下情况:

```
{
  "org.spring[email protected]77856cc5": 10100,
  "o[email protected]4f6fd101": 10000,
  "or[email protected]32d22650": -1,
  "[email protected]6459d9": 2147483647,
  "[email protected]5e0": 2147483647,
  "[email protected]d23": 0,
  "org.s[email protected]135064ea": 2147483637,
  "[email protected]23c05889": 2147483646
}
```

响应包含已到位的全局过滤器的详细信息。对于每个全局过滤器,有一个字符串表示过滤器对象(例如,`org.spring[[email protected]](/cdn-cgi/l/email-protection)77856cc5`)和相应的`get()`在过滤器链中。}

#### [](#gateway-route-filters)[15.2.2.路由过滤器](#gateway-route-filters) ####

要检索应用于路由的[“GatewayFilter”工厂](#gatewayfilter-factories),请对`GET`请求`/actuator/gateway/routefilters`。由此产生的反应类似于以下情况:

```
{
  "[[email protected] configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null,
  "[[email protected] configClass = Object]": null,
  "[[email protected] configClass = Object]": null
}
```

响应包含应用于任何特定路径的`GatewayFilter`工厂的详细信息。对于每个工厂,都有一个对应对象的字符串表示(例如,`[[[email protected]](/cdn-cgi/l/email-protection) configClass = Object]`)。请注意,`null`值是由于端点控制器的实现不完整造成的,因为它试图设置过滤器链中对象的顺序,这不适用于`GatewayFilter`工厂对象。

### [](#refreshing-the-route-cache)[15.3.刷新路径缓存](#refreshing-the-route-cache) ###

要清除路由缓存,请对`POST`请求`/actuator/gateway/refresh`。该请求返回一个没有响应体的 200。

### [](#retrieving-the-routes-defined-in-the-gateway)[15.4.检索在网关中定义的路由](#retrieving-the-routes-defined-in-the-gateway) ###

要检索在网关中定义的路由,请对`GET`请求`/actuator/gateway/routes`。由此产生的反应类似于以下情况:

```
[{
  "route_id": "first_route",
  "route_object": {
    "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/[email protected]",
    "filters": [
      "OrderedGatewayFilter{delegate=org.springframework.cloud.gateway.filter.factory.PreserveHostHeaderGatewayFilterFactory$$Lambda$436/[email protected], order=0}"
    ]
  },
  "order": 0
},
{
  "route_id": "second_route",
  "route_object": {
    "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/[email protected]",
    "filters": []
  },
  "order": 0
}]
```

响应包含网关中定义的所有路由的详细信息。下表描述了响应的每个元素(每个都是路由)的结构:

|          Path          | Type |说明|
|------------------------|------|-------------------------------------------------------------------------------|
|       `route_id`       |String|路线 ID。|
|`route_object.predicate`|Object|路线谓词。|
| `route_object.filters` |Array |将[“GatewayFilter”工厂](#gatewayfilter-factories)应用于该路线。|
|        `order`         |Number|路线顺序。|

### [](#gateway-retrieving-information-about-a-particular-route)[15.5.检索有关特定路线的信息](#gateway-retrieving-information-about-a-particular-route) ###

要检索有关单个路由的信息,请对`GET`请求`/actuator/gateway/routes/{id}`(例如,`/actuator/gateway/routes/first_route`)。由此产生的反应类似于以下情况:

```
{
  "id": "first_route",
  "predicates": [{
    "name": "Path",
    "args": {"_genkey_0":"/first"}
  }],
  "filters": [],
  "uri": "https://www.uri-destination.org",
  "order": 0
}
```

下表描述了响应的结构:

|    Path    | Type |说明|
|------------|------|------------------------------------------------------------------------------------------------------|
|    `id`    |String|路线 ID。|
|`predicates`|Array |路由谓词的集合。每个项定义给定谓词的名称和参数。|
| `filters`  |Array |应用于路由的过滤器的集合。|
|   `uri`    |String|路线的目的地 URI。|
|  `order`   |Number|路线顺序。|

### [](#creating-and-deleting-a-particular-route)[15.6.创建和删除特定的路由](#creating-and-deleting-a-particular-route) ###

要创建路由,请使用指定路由字段的 JSON 主体对`POST`请求`/gateway/routes/{id_route_to_create}`(参见)。

要删除一个路由,请对`DELETE`请求`/gateway/routes/{id_route_to_delete}`。

### [](#recap-the-list-of-all-endpoints)[15.7.回顾:所有端点的列表](#recap-the-list-of-all-endpoints) ###

下面的 FolloiWNG 表总结了 Spring 云网关执行器端点(请注意,每个端点都以`/actuator/gateway`作为基本路径):

|      ID       |HTTP Method|说明|
|---------------|-----------|-----------------------------------------------------------------------------|
|`globalfilters`|    GET    |显示应用于路由的全局筛选器列表。|
|`routefilters` |    GET    |显示应用于特定路径的`GatewayFilter`工厂的列表。|
|   `refresh`   |   POST    |清除路由缓存。|
|   `routes`    |    GET    |显示在网关中定义的路由列表。|
| `routes/{id}` |    GET    |显示有关特定路线的信息。|
| `routes/{id}` |   POST    |为网关添加了一条新的路径。|
| `routes/{id}` |  DELETE   |从网关删除现有的路由。|

### [](#sharing-routes-between-multiple-gateway-instances)[15.8.在多个网关实例之间共享路由](#sharing-routes-between-multiple-gateway-instances) ###

Spring 云网关提供了两种`RouteDefinitionRepository`实现方式。第一个是“InmemoryRouteDefinitionRepository”,它只存在于一个网关实例的内存中。这种类型的存储库不适合跨多个网关实例填充路由。

为了跨 Spring 个云网关实例的集群共享路由,可以使用`RedisRouteDefinitionRepository`。要启用这种存储库,以下属性必须设置为 true:`spring.cloud.gateway.redis-route-definition-repository.enabled`同样,对于 RedisrateLimiter 过滤器工厂,它需要使用 Spring-boot-starter-data-redis-active Spring boot starter。

[](#troubleshooting)[16.故障排除](#troubleshooting)
----------

本节介绍了使用 Spring 云网关时可能出现的常见问题。

### [](#log-levels)[16.1.日志级别](#log-levels) ###

以下记录器可能在`DEBUG`和`TRACE`级别包含有价值的故障排除信息:

* `org.springframework.cloud.gateway`

* `org.springframework.http.server.reactive`

* `org.springframework.web.reactive`

* `org.springframework.boot.autoconfigure.web`

* `reactor.netty`

* `redisratelimiter`

### [](#wiretap)[16.2. Wiretap](#wiretap) ###

反应堆网络`HttpClient`和`HttpServer`可以启用窃听功能。当与将`reactor.netty`日志级别设置为`DEBUG`或`HttpServer`相结合时,它启用了对信息的日志记录,例如通过连接发送和接收的标题和主体。要启用窃听,请分别为`HttpServer`和设置`spring.cloud.gateway.httpclient.wiretap=true`。

[](#developer-guide)[17.开发者指南](#developer-guide)
----------

这些是编写网关的一些自定义组件的基本指南。

### [](#writing-custom-route-predicate-factories)[17.1.编写自定义路由谓词工厂](#writing-custom-route-predicate-factories) ###

为了编写路由谓词,你需要将`RoutePredicateFactory`实现为 Bean。有一个名为`AbstractRoutePredicateFactory`的抽象类,你可以对其进行扩展。

MyRoutepredicateFactory.java

```
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        // grab configuration from Config object
        return exchange -> {
            //grab the request
            ServerHttpRequest request = exchange.getRequest();
            //take information from the request to see if it
            //matches configuration.
            return matches(config, request);
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}
```

### [](#writing-custom-gatewayfilter-factories)[17.2.编写自定义网关过滤器工厂](#writing-custom-gatewayfilter-factories) ###

要编写`GatewayFilter`,你必须将`GatewayFilterFactory`实现为 Bean。你可以扩展一个名为`AbstractGatewayFilterFactory`的抽象类。下面的例子说明了如何做到这一点:

例 74。Pregatewayfilterfactory.java

```
@Component
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {

    public PreGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        // grab configuration from Config object
        return (exchange, chain) -> {
            //If you want to build a "pre" filter you need to manipulate the
            //request before calling chain.filter
            ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
            //use builder to manipulate the request
            return chain.filter(exchange.mutate().request(builder.build()).build());
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}
```

Postgatewayfilterfactory.java

```
@Component
public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {

    public PostGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        // grab configuration from Config object
        return (exchange, chain) -> {
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                ServerHttpResponse response = exchange.getResponse();
                //Manipulate the response in some way
            }));
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}
```

#### [](#naming-custom-filters-and-references-in-configuration)[17.2.1.在配置中命名自定义过滤器和引用](#naming-custom-filters-and-references-in-configuration) ####

自定义过滤器类名称应该以`GatewayFilterFactory`结尾。

例如,要在配置文件中引用名为`Something`的过滤器,该过滤器必须位于名为[](#log-levels)的类中。

|   |可以创建一个没有“gatewayfilterfactory”后缀的网关过滤器,例如`class AnotherThing`。这个过滤器可以在配置文件中被`AnotherThing`引用为`AnotherThing`。这是**不是**所支持的命名<br/>约定,该语法可能会在未来的版本中删除。请更新过滤器<br/>名称以使其兼容。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#writing-custom-global-filters)[17.3.编写自定义全局过滤器](#writing-custom-global-filters) ###

要编写自定义的全局过滤器,你必须将[](#writing-custom-global-filters)接口实现为 Bean。这将过滤器应用于所有请求。

以下示例分别展示了如何设置全局 pre 和 post 过滤器:

```
@Bean
public GlobalFilter customGlobalFilter() {
    return (exchange, chain) -> exchange.getPrincipal()
        .map(Principal::getName)
        .defaultIfEmpty("Default User")
        .map(userName -> {
          //adds header to proxied request
          exchange.getRequest().mutate().header("CUSTOM-REQUEST-HEADER", userName).build();
          return exchange;
        })
        .flatMap(chain::filter);
}

@Bean
public GlobalFilter customGlobalPostFilter() {
    return (exchange, chain) -> chain.filter(exchange)
        .then(Mono.just(exchange))
        .map(serverWebExchange -> {
          //adds header to response
          serverWebExchange.getResponse().getHeaders().set("CUSTOM-RESPONSE-HEADER",
              HttpStatus.OK.equals(serverWebExchange.getResponse().getStatusCode()) ? "It worked": "It did not work");
          return serverWebExchange;
        })
        .then();
}
```

[](#building-a-simple-gateway-by-using-spring-mvc-or-webflux)[18. Building a Simple Gateway by Using Spring MVC or Webflux](#building-a-simple-gateway-by-using-spring-mvc-or-webflux)
----------

|   |下面描述了一种替代样式的网关。以前的文件都不适用于下面的内容。|
|---|--------------------------------------------------------------------------------------------------------------|

Spring 云网关提供了一种名为`ProxyExchange`的实用工具对象。你可以在常规的 Spring Web 处理程序中使用它作为方法参数。它通过镜像 HTTP 动词的方法支持基本的下游 HTTP 交换。对于 MVC,它还支持通过`forward()`方法转发到本地处理程序。要使用`ProxyExchange`,在 Classpath 中包含正确的模块(`spring-cloud-gateway-mvc`或`spring-cloud-gateway-webflux`)。

下面的 MVC 示例将请求代理到`/test`下游的远程服务器:

```
@RestController
@SpringBootApplication
public class GatewaySampleApplication {

    @Value("${remote.home}")
    private URI home;

    @GetMapping("/test")
    public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception {
        return proxy.uri(home.toString() + "/image/png").get();
    }

}
```

下面的示例对 WebFlux 做了相同的处理:

```
@RestController
@SpringBootApplication
public class GatewaySampleApplication {

    @Value("${remote.home}")
    private URI home;

    @GetMapping("/test")
    public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception {
        return proxy.uri(home.toString() + "/image/png").get();
    }

}
```

`ProxyExchange`上的便利方法使处理程序方法能够发现并增强传入请求的 URI 路径。例如,你可能希望提取路径的尾随元素,以便向下游传递它们:

```
@GetMapping("/proxy/path/**")
public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) throws Exception {
  String path = proxy.path("/proxy/path/");
  return proxy.uri(home.toString() + "/foos/" + path).get();
}
```

Spring MVC 和 WebFlux 的所有特性都可用于网关处理程序方法。因此,例如,你可以插入请求头和查询参数,并且可以通过映射注释中的声明来约束传入的请求。有关这些特性的更多详细信息,请参见 Spring MVC 中`@RequestMapping`的文档。

你可以使用`ProxyExchange`上的`header()`方法向下游响应添加标题。

你还可以通过向`get()`方法(和其他方法)添加一个映射器来操作响应头(以及响应中喜欢的任何其他方法)。映射器是一个`ResponseEntity`,它接收传入的`ResponseEntity`并将其转换为传出的。

为“敏感”头(默认情况下,`cookie`和`authorization`)和“代理”头(x-forwarded-*`)提供了一流的支持。

[](#configuration-properties)[19.配置属性](#configuration-properties)
----------

要查看所有 Spring 云网关相关配置属性的列表,请参见[the appendix](appendix.html)

如果{{{i[’GoogleAnalyticsObject’]=r;i[r]=i[r]|function(){q=i[r].push(参数)},i[r].l=1\*new date();a=s.createElement(o),m=s.getelementsbyName(0);a.parentsName(1);a.A.SRC=g;m.M.analytnode(gua,m.com.com);(google=document=’,’,’’’’’’’’’’’),’documents’,’’’.’’’’’’’’’’,’’’