springcloud搭建 初级人员的使用搭建。sentinel使用官网有详细的使用方法

代码仓库地址:https://github.com/zhaoyiwen-wuxian/shop-trench

bash 复制代码
package com.trench.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**全局拦截器进行拦截未登录等操作
 * 当然可以拦截其他等操作,需要进行根据自己等需求从而进行逻辑添加
 *
 *
 * */
@Component
public class AuthGatewayFilters implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token=exchange.getRequest().getQueryParams().getFirst("token");
        if(StringUtils.isEmpty(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
}
bash 复制代码
package com.trench.filters;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
/**局部过滤器使用方法*/
public class TimeGatewayFiltersFactory extends
        AbstractGatewayFilterFactory<TimeGatewayFiltersFactory.Config> {


    public TimeGatewayFiltersFactory(){
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("show");
    }

    @Override
    public GatewayFilter apply(TimeGatewayFiltersFactory.Config config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                if (!config.isShow()){
                   return chain.filter(exchange);
                }
                long start = System.currentTimeMillis();

                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    //添加自己想要进行存储的逻辑。可以存储数据库red is/es等中
                    log.info("请求耗时:{}",System.currentTimeMillis()-start);
                }));
            }
        };
    }

    @Getter
    @Setter
    public static class Config {
        private boolean show;
    }
}

spring:

application:

name: api-gateway

cloud:

nacos:

config:

file-extension: yaml

server-addr: 127.0.0.1:8848

#添加其他的配置文件的读取

shared-configs:

  • dataId: redis.yaml

refresh: true #是否支持动态刷新

profiles:

active: dev

复制代码
#在nacos中创建一个api-gateway-dev.yaml 后将application.yml文件中数据全部copy到nacos中,并且删除application.yml文件

#appConfig:

#name: gateway 动态更新

#共享的环境配置:api-gateway.yaml 将公共的丢到这个里面。

bash 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.trench</groupId>
        <artifactId>shop-trench</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>shop-gateway</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-cloud-alibaba-nacos-discovery.version>2.1.1.RELEASE</spring-cloud-alibaba-nacos-discovery.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
            <version>${spring-cloud-alibaba-nacos-discovery.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--sleuth-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
    </dependencies>
</project>
bash 复制代码
package com.trench.util.snow;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SnowFlakeFactory {
        /**
         * 默认的雪花算法句柄
         */
        private static final String DEFAULT_SNOW_FLAKE = "snow_flake";
        /**
         * 缓存SnowFlake对象
         */
        private static ConcurrentMap<String, SnowFlake> snowFlakeCache = new
                ConcurrentHashMap<>(2);
        public static SnowFlake getSnowFlake(long datacenterId, long machineId) {
            return new SnowFlake(datacenterId, machineId);
        }
        public static SnowFlake getSnowFlake() {
            return new SnowFlake(SnowFlakeLoader.getDataCenterId(), SnowFlakeLoader.getMachineId());
        }
        public static SnowFlake getSnowFlakeFromCache() {
            SnowFlake snowFlake = snowFlakeCache.get(DEFAULT_SNOW_FLAKE);
            if(snowFlake == null) {
                snowFlake = new SnowFlake(SnowFlakeLoader.getDataCenterId(),
                        SnowFlakeLoader.getMachineId());
                snowFlakeCache.put(DEFAULT_SNOW_FLAKE, snowFlake);
            }
            return snowFlake;
        }
        /**
         * 根据数据中心id和机器id从缓存中获取全局id
         * @param dataCenterId: 取值为1~31
         * @param machineId: 取值为1~31
         */
        public static SnowFlake getSnowFlakeByDataCenterIdAndMachineIdFromCache(Long dataCenterId, Long machineId) {
            if (dataCenterId > SnowFlake.getMaxDataCeneterNum() || dataCenterId < 0) {
                throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
            }
            if (machineId > SnowFlake.getMaxMachineNum() || machineId < 0) {
                throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
            }
            String key =
                    DEFAULT_SNOW_FLAKE.concat("_").concat(String.valueOf(dataCenterId)).concat("_").
                            concat(String.valueOf(machineId));
            SnowFlake snowFlake = snowFlakeCache.get(key);
            if(snowFlake == null) {
                snowFlake = new SnowFlake(dataCenterId, machineId);
                snowFlakeCache.put(key, snowFlake);
            }
            return snowFlake;
        }
}
bash 复制代码
package com.trench.util.snow;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SnowFlakeLoader {
    public static final String DATA_CENTER_ID = "data.center.id";
    public static final String MACHINE_ID = "machine.id";
    private volatile static Properties instance;
    static {
        InputStream in =
                SnowFlakeLoader.class.getClassLoader().getResourceAsStream("snowflake.properties");
                        instance = new Properties();
        try {
            instance.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static String getStringValue(String key){
        if(instance == null) return "";
        return instance.getProperty(key, "");
    }
    private static Long getLongValue(String key){
        String v = getStringValue(key);
        return (v == null || v.trim().isEmpty()) ? 0 : Long.parseLong(v);
    }
    public static Long getDataCenterId() {
        return getLongValue(DATA_CENTER_ID);
    }
    public static Long getMachineId() {
        return getLongValue(MACHINE_ID);
    }
}
bash 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.trench</groupId>
    <artifactId>shop-trench</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>shop-product-api</module>
        <module>shop-product-server</module>
        <module>shop-util</module>
        <module>shop-order-api</module>
        <module>shop-order-server</module>
        <module>shop-gateway</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <spring-cloud-dependencies.version>Hoxton.SR8</spring-cloud-dependencies.version>
        <spring-cloud-alibaba-dependencies.version>2.2.3.RELEASE</spring-cloud-alibaba-dependencies.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>
相关推荐
今天背单词了吗980几秒前
算法学习笔记:8.Bellman-Ford 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·后端·算法·最短路径问题
天天摸鱼的java工程师3 分钟前
使用 Spring Boot 整合高德地图实现路线规划功能
java·后端
阿杆5 分钟前
😡同事查日志太慢,我现场教他一套 grep 组合拳!
linux·后端
PetterHillWater6 分钟前
基于Trae智能复杂项目重构实践
后端·aigc
凌览19 分钟前
有了 25k Star 的MediaCrawler爬虫库加持,三分钟搞定某红书、某音等平台爬取!
前端·后端·python
这里有鱼汤31 分钟前
给你的DeepSeek装上实时行情,让他帮你炒股
后端·python·mcp
咖啡啡不加糖33 分钟前
暴力破解漏洞与命令执行漏洞
java·后端·web安全
风象南36 分钟前
SpringBoot敏感配置项加密与解密实战
java·spring boot·后端
ん贤1 小时前
RESTful风格
后端·go·restful
Humbunklung1 小时前
Rust方法语法:赋予结构体行为的力量
开发语言·后端·rust