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>
相关推荐
camellias_4 小时前
SpringBoot(二十三)SpringBoot集成JWT
java·spring boot·后端
tebukaopu1484 小时前
springboot如何获取控制层get和Post入参
java·spring boot·后端
昔我往昔4 小时前
SpringBoot 创建对象常见的几种方式
java·spring boot·后端
武昌库里写JAVA4 小时前
机器学习笔记2 - 机器学习的一般流程
spring boot·spring·毕业设计·layui·课程设计
灭掉c与java4 小时前
第三章springboot数据访问
java·spring boot·后端
啊松同学4 小时前
【Java】设计模式——工厂模式
java·后端·设计模式
枫叶_v5 小时前
【SpringBoot】20 同步调用、异步调用、异步回调
java·spring boot·后端
源码12156 小时前
ASP.NET MVC宠物商城系统
后端·asp.net·宠物
Ai 编码助手7 小时前
Go语言 实现将中文转化为拼音
开发语言·后端·golang
hummhumm7 小时前
第 12 章 - Go语言 方法
java·开发语言·javascript·后端·python·sql·golang