版本控制 pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<!-- 此管理不加 会出问题【 Spring Boot [2.0.6.RELEASE] is not compatible with this Spring Cloud release train】-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource> <!-- 将jar统一打进lib目录下 -->
<directory>src/main/resources/lib</directory>
<targetPath>BOOT-INF/lib</targetPath>
</resource>
</resources>
<!-- 配置打包及打包后的项目存放路径 outputDirectory -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<finalName>${project.name}</finalName>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
<outputDirectory>E:/compose/squarepay</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
1:服务注册与发现(nacos)
启动命令:
Linux/Unix/Mac : 单机模式:# sh startup.sh -m standalone 集群模式:# sh startup.sh
Windows :cmd startup.cmd
0.8版本同时支持单机和集群模式的数据库使用,默认账号密码都是nacos
若使用数据库 则配置application.properties:
若需要修改账号密码,则使用security的加密 【 new BCryptPasswordEncoder().encode(“你的密码”) 】
Spring.datasource.platform=mysql # 集群模式下不加这个可以,但是单机模式下不加这句貌似无法使用数据库
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=youknow
db.password=youknow
启动后打开:127.0.0.1:8848/nacos/index.html
2:服务提供者
注:为保证方便此项目并未实际使用数据库
pom:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId> org.springframework.cloud </groupId >
<artifactId> spring-cloud-starter-alibaba-nacos-discovery </artifactId >
</dependency>
<!-- 使用配置中心的方式-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
Application.java 启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// 注入配置文件上下文 动态刷新 @value 貌似不支持动态刷新
@Autowired
private ConfigurableApplicationContext applicationContext;
@GetMapping(value = "/getBook/{id}")
public Object getBook(@PathVariable Integer id) {
System.out.println("<><>><><><><>><><>");
return "当前实例------> A"+ "当前端口------>"+ applicationContext.getEnvironment().getProperty("server.port");
}
}
bootstrap.properties
# 这里的应用名对应 Nacos Config 中的 Data ID,
spring.application.name=book-crud-sca-provider-config
# 指定配置名为 book-crud-sca-provider-config 的配置文件,下面配置是后缀
spring.cloud.nacos.config.file-extension=yaml
# 注册中心 的地址
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
配置中心截图:
3:Gateway网关
pom:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
application.yml:
server:
port: 9000
spring:
application:
name: book-sca-gateway
cloud:
# 将网关注册到nacos
nacos:
discovery:
server-addr: 127.0.0.1:8848
# 路由网关配置
gateway:
# 启用
discovery:
locator:
enabled: true
# 配置规则
routes:
# id 起别名
- id: service
# 以 lb:// 开头,后面的是注册在 Nacos 上的服务名
uri: lb://book-crud-sca-provider
predicates:
# 匹配 GET 和 POST 请求
- Method=GET,POST
# 匹配路径 /service 此路径下的请求通过这里
- Path=/service/**
filters:
# 必须加这个,否则会将/service/也会匹配进最终的路径中去 出现404
- StripPrefix=1
#以上配置并未使用熔断降级,以后提到
GatewayApplication.java 启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
AuthFilter.java 过滤器:
package com.ccm.filters;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* 鉴权过滤器
*/
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getQueryParams().getFirst("token");
if (token == null || token.isEmpty()) {
ServerHttpResponse response = exchange.getResponse();
// 错误信息
JSONObject json=new JSONObject();
json.put("code","501");
json.put("massage","token 不能为空");
try {
// 返回错误信息
DataBuffer buffer = response.bufferFactory().wrap(json.toString().getBytes());
response.setStatusCode(HttpStatus.UNAUTHORIZED); //设置浏览器返回的回执码
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
return chain.filter(exchange);
}
/**
* 设置过滤器的执行顺序
* @return
*/
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
配置完成
需要负载均衡时,保证项目名相同即可。