feat:optimize examples. (#1188)

pull/1190/head
Haotian Zhang 1 year ago committed by GitHub
parent 5119045ea6
commit d5dac7678a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -15,3 +15,4 @@
- [feat: add metadata transfer for http header via spring.cloud.tencent.metadata.headers.](https://github.com/Tencent/spring-cloud-tencent/pull/1176)
- [fix:remove bcprov-jdk15on dependency.](https://github.com/Tencent/spring-cloud-tencent/pull/1180)
- [feat:support configuration encryption.](https://github.com/Tencent/spring-cloud-tencent/pull/1184)
- [feat:optimize examples.](https://github.com/Tencent/spring-cloud-tencent/pull/1188)

@ -49,18 +49,6 @@
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-contract</artifactId>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>

@ -15,7 +15,30 @@ spring:
nacos:
discovery:
server-addr: 127.0.0.1:8848
# consul:
# port: 8500
# host: 127.0.0.1
# enabled: true
# discovery:
# enabled: true
# register: true
# health-check-path: /actuator/health
# health-check-interval: 10s
# instance-id: ${spring.application.name}:${server.port}
# service-name: ${spring.application.name}
# ip-address: localhost
# prefer-ip-address: true
# nacos:
# enabled: true
# password: nacos
# username: nacos
# context-path: /nacos
# discovery:
# enabled: true
# register-enabled: true
# group: polaris
# server-addr: 127.0.0.1:8848
# cluster-name: polaris
feign:
circuitbreaker:
enabled: true

@ -1,66 +0,0 @@
# Spring Cloud Polaris Circuitbreaker example
## 样例简介
本样例将介绍如何在Spring Cloud项目中使用```spring-cloud-starter-tencent-polaris-circuitbreaker```以使用其各项功能。
本样例包括被调方```polaris-circuitbreaker-callee-service```、```polaris-circuitbreaker-callee-service2```和主调方```polaris-circuitbreaker-feign-example```、```polaris-circuitbreaker-gateway-example```、```polaris-circuitbreaker-webclient-example```。
## 使用说明
### 修改配置
配置如下所示。其中,${ip}和${port}为Polaris后端服务的IP地址与端口号。
```yaml
spring:
application:
name: ${application.name}
cloud:
polaris:
address: ${ip}:${port}
```
### 启动样例
#### 启动Polaris后端服务
参考[Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)。
#### 启动被调应用
分别启动```polaris-circuitbreaker-example/polaris-circuitbreaker-callee-service```、```polaris-circuitbreaker-example/polaris-circuitbreaker-callee-service2```
#### 启动主调应用
##### 启动Feign并验证
启动```polaris-circuitbreaker-example/polaris-circuitbreaker-feign-example```。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromPolaris'`, 验证熔断和Polaris-server远程拉取降级。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromCode'`, 验证熔断和代码降级。
##### 启动RestTemplate并验证
启动```polaris-circuitbreaker-example/polaris-circuitbreaker-resttemplate-example```。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromPolaris'`, 验证熔断和Polaris-server远程拉取降级。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromCode'`, 验证熔断和代码降级。
##### 启动WebClient并验证
启动```polaris-circuitbreaker-example/polaris-circuitbreaker-webclient-example```。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo'`, 验证熔断和代码降级。
##### 启动SCG并验证
启动```polaris-circuitbreaker-example/polaris-circuitbreaker-gateway-example```。
发送请求`curl --location --request GET 'http://127.0.0.1:48080/polaris-circuitbreaker-callee-service/example/service/b/info'`, 验证熔断和代码降级。
修改```polaris-circuitbreaker-example/polaris-circuitbreaker-gateway-example/resources/bootstrap.yml```。删除本地fallback方法并重启验证熔断和Polaris-server远程拉取降级。

@ -1,66 +0,0 @@
# Spring Cloud Polaris Circuitbreaker example
## Example Introduction
This example shows how to use```spring-cloud-starter-tencent-polaris-circuitbreaker```in Spring Cloud project for its features.
This example contains callee-service```polaris-circuitbreaker-callee-service```、```polaris-circuitbreaker-callee-service2```and caller-service```polaris-circuitbreaker-feign-example```、```polaris-circuitbreaker-gateway-example```、```polaris-circuitbreaker-webclient-example```.
## Instruction
### Configuration
The configuration is as the following shows. ${ip} and ${port} are Polaris backend IP address and port number.
```yaml
spring:
application:
name: ${application.name}
cloud:
polaris:
address: ${ip}:${port}
```
### Launching Example
#### Launching Polaris Backend Service
Reference to [Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)
#### Launching callee service
Launching```polaris-circuitbreaker-example/polaris-circuitbreaker-callee-service```、```polaris-circuitbreaker-example/polaris-circuitbreaker-callee-service2```
#### Launching caller service
##### Launching Feign and Verify
Launching```polaris-circuitbreaker-example/polaris-circuitbreaker-feign-example```.
Sending request`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromPolaris'`, Verify circuit breaker and fallback from Polaris-server.
Sending request`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromCode'`, Verify circuit breaker and fallback from code.
##### Launching RestTemplate and Verify
Launching```polaris-circuitbreaker-example/polaris-circuitbreaker-resttemplate-example```.
Sending request`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromPolaris'`, Verify circuit breaker and fallback from Polaris-server.
Sending request`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo/fallbackFromCode'`, Verify circuit breaker and fallback from code.
##### Launching WebClient and Verify
Launching```polaris-circuitbreaker-example/polaris-circuitbreaker-webclient-example```。
Sending request`curl --location --request GET 'http://127.0.0.1:48080/example/service/a/getBServiceInfo'`, Verify circuit breaker and fallback from code.
##### Launching SCG and Verify
Launching```polaris-circuitbreaker-example/polaris-circuitbreaker-gateway-example```。
Sending request`curl --location --request GET 'http://127.0.0.1:48080/polaris-circuitbreaker-callee-service/example/service/b/info'`, Verify circuit breaker and fallback from code.
Changing```polaris-circuitbreaker-example/polaris-circuitbreaker-gateway-example/resources/bootstrap.yml```, delete local fallback and restart, Verify circuit breaker and fallback from Polaris-server.

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-callee-service</artifactId>
<name>Polaris Circuit Breaker Callee Example</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Circuit breaker example callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class ServiceB {
public static void main(String[] args) {
SpringApplication.run(ServiceB.class, args);
}
}

@ -1,55 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.circuitbreaker.example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Service B Controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/example/service/b")
public class ServiceBController {
/**
* Get service information.
*
* @return service information
*/
@GetMapping("/info")
public String info() {
return "hello world ! I'm a service B1";
}
@GetMapping("/health")
public String health() {
System.out.println("health check: 200 instance");
return "hello world ! I'm a service B1";
}
@GetMapping("/health-svc")
public String healthsvc() {
System.out.println("health-svc check: 200 instance");
return "hello world ! I'm a service B1";
}
}

@ -1,13 +0,0 @@
server:
port: 48081
spring:
application:
name: polaris-circuitbreaker-callee-service
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
stat:
enabled: true
port: 28082

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-callee-service2</artifactId>
<name>Polaris Circuit Breaker Callee Example 2</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,35 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.ciruitbreaker.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Circuit breaker example callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class ServiceB2 {
public static void main(String[] args) {
SpringApplication.run(ServiceB2.class, args);
}
}

@ -1,98 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.ciruitbreaker.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* Service B Controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/example/service/b")
public class ServiceBController {
private static final Logger LOG = LoggerFactory.getLogger(ServiceBController.class);
private boolean ifBadGateway = true;
private boolean ifDelay = true;
@GetMapping("/setBadGateway")
public void setBadGateway(@RequestParam boolean param) {
if (param) {
LOG.info("info is set to return HttpStatus.BAD_GATEWAY.");
}
else {
LOG.info("info is set to return HttpStatus.OK.");
}
this.ifBadGateway = param;
}
@GetMapping("/setDelay")
public void setDelay(@RequestParam boolean param) {
if (param) {
LOG.info("info is set to delay 100ms.");
}
else {
LOG.info("info is set to no delay.");
}
this.ifDelay = param;
}
/**
* Get service information.
*
* @return service information
*/
@GetMapping("/info")
public ResponseEntity<String> info() throws InterruptedException {
if (ifBadGateway) {
return new ResponseEntity<>("failed for call my service", HttpStatus.BAD_GATEWAY);
}
if (ifDelay) {
Thread.sleep(100);
}
return new ResponseEntity<>("hello world ! I'm a service B2", HttpStatus.OK);
}
@GetMapping("/health")
@ResponseStatus(value = HttpStatus.BAD_GATEWAY, reason = "failed for call my service")
public String health() {
System.out.println("health check: 502 instance");
return "hello world ! I'm a service B1";
}
@GetMapping("/health-svc")
@ResponseStatus(value = HttpStatus.BAD_GATEWAY, reason = "failed for call my service")
public String healthsvc() {
System.out.println("health-svc check: 502 instance");
return "hello world ! I'm a service B1";
}
}

@ -1,13 +0,0 @@
server:
port: 48082
spring:
application:
name: polaris-circuitbreaker-callee-service
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
stat:
enabled: true
port: 28083

@ -1,82 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-feign-example</artifactId>
<name>Polaris Circuit Breaker Feign Example</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-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-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-circuitbreaker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,59 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.feign.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Circuit breaker example caller controller.
*
* @author sean yu
*/
@RestController
@RequestMapping("/example/service/a")
public class ServiceAController {
@Autowired
private ProviderB polarisServiceB;
@Autowired
private ProviderBWithFallback providerBWithFallback;
/**
* Get info of Service B by Feign.
* @return info of Service B
*/
@GetMapping("/getBServiceInfo/fallbackFromCode")
public String getBServiceInfoFallbackFromCode() {
return providerBWithFallback.info();
}
/**
* Get info of Service B by Feign.
* @return info of Service B
*/
@GetMapping("/getBServiceInfo/fallbackFromPolaris")
public String getBServiceInfoFallbackFromPolaris() {
return polarisServiceB.info();
}
}

@ -1,38 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.circuitbreaker.feign.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* Circuit breaker example caller application.
*
* @author sean yu
*/
@SpringBootApplication
@EnableFeignClients
public class ServiceAFeign {
public static void main(String[] args) {
SpringApplication.run(ServiceAFeign.class, args);
}
}

@ -1,29 +0,0 @@
server:
port: 48080
spring:
application:
name: polaris-circuitbreaker-feign-example
cloud:
openfeign:
circuitbreaker:
enabled: true
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
loadbalancer:
enabled: true
circuitbreaker:
enabled: true
logging:
level:
root: info
com.tencent.cloud: debug
management:
endpoints:
web:
exposure:
include:
- polaris-circuit-breaker

@ -1,92 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-gateway-example</artifactId>
<name>Polaris Circuit Breaker Gateway Example</name>
<dependencies>
<dependency>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
<groupId>com.tencent.cloud</groupId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-circuitbreaker</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-router</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-gateway-plugin</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-metadata-transfer</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-featureenv-plugin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,35 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.gateway.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SCG application.
*
* @author sean yu
*/
@SpringBootApplication
public class GatewayScgApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayScgApplication.class, args);
}
}

@ -1,65 +0,0 @@
server:
session-timeout: 1800
port: 48080
spring:
application:
name: GatewayScgService
cloud:
tencent:
plugin:
scg:
staining:
enabled: true
rule-staining:
enabled: true
router:
feature-env:
enabled: true
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
gateway:
discovery:
locator:
enabled: true
'predicates[0]':
name: Path
args:
patterns: '''/'' + serviceId + ''/**'''
'filters[0]':
name: RewritePath
args:
regexp: '''/'' + serviceId + ''/(?<remaining>.*)'''
replacement: '''/$\{remaining}'''
'filters[1]':
name: CircuitBreaker
args:
# statusCodes 缺省时会自动识别 "5**" 为错误
# statusCodes: '''404,5**'''
# fallbackUri 缺省时会在熔断触发后拉取 plaris server 配置的降级作为 response
fallbackUri: '''forward:/polaris-fallback'''
# routes:
# - id: polaris-circuitbreaker-callee-service
# uri: lb://polaris-circuitbreaker-callee-service
# predicates:
# - Path=/polaris-circuitbreaker-callee-service/**
# filters:
# - StripPrefix=1
# - name: CircuitBreaker
# args:
# statusCodes: 502
# fallbackUri: forward:/polaris-fallback
logging:
level:
root: info
com.tencent.polaris.discovery.client.flow.RegisterFlow: off
com.tencent.polaris.plugins.registry: off
com.tencent.cloud: debug
management:
endpoints:
web:
exposure:
include:
- polaris-circuit-breaker

@ -1,77 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-resttemplate-example</artifactId>
<name>Polaris Circuit Breaker RestTemplate Example</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-circuitbreaker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,74 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.resttemplate.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Circuit breaker example caller controller.
*
* @author sean yu
*/
@RestController
@RequestMapping("/example/service/a")
public class ServiceAController {
@Autowired
@Qualifier("defaultRestTemplate")
private RestTemplate defaultRestTemplate;
@Autowired
@Qualifier("restTemplateFallbackFromPolaris")
private RestTemplate restTemplateFallbackFromPolaris;
@Autowired
@Qualifier("restTemplateFallbackFromCode")
private RestTemplate restTemplateFallbackFromCode;
@Autowired
private CircuitBreakerFactory circuitBreakerFactory;
@GetMapping("/getBServiceInfo")
public String getBServiceInfo() {
return circuitBreakerFactory
.create("polaris-circuitbreaker-callee-service#/example/service/b/info")
.run(() ->
defaultRestTemplate.getForObject("/example/service/b/info", String.class),
throwable -> "trigger the refuse for service b"
);
}
@GetMapping("/getBServiceInfo/fallbackFromPolaris")
public ResponseEntity<String> getBServiceInfoFallback() {
return restTemplateFallbackFromPolaris.getForEntity("/example/service/b/info", String.class);
}
@GetMapping("/getBServiceInfo/fallbackFromCode")
public ResponseEntity<String> getBServiceInfoFallbackClass() {
return restTemplateFallbackFromCode.getForEntity("/example/service/b/info", String.class);
}
}

@ -1,71 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.circuitbreaker.resttemplate.example;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
/**
* Circuit breaker example caller application.
*
* @author sean yu
*/
@SpringBootApplication
public class ServiceAResTemplate {
public static void main(String[] args) {
SpringApplication.run(ServiceAResTemplate.class, args);
}
@Bean
@LoadBalanced
public RestTemplate defaultRestTemplate() {
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://polaris-circuitbreaker-callee-service");
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);
return restTemplate;
}
@Bean
@LoadBalanced
@PolarisCircuitBreaker
public RestTemplate restTemplateFallbackFromPolaris() {
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://polaris-circuitbreaker-callee-service");
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);
return restTemplate;
}
@Bean
@LoadBalanced
@PolarisCircuitBreaker(fallbackClass = CustomFallback.class)
public RestTemplate restTemplateFallbackFromCode() {
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://polaris-circuitbreaker-callee-service");
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);
return restTemplate;
}
}

@ -1,26 +0,0 @@
server:
port: 48080
spring:
application:
name: polaris-circuitbreaker-resttemplate-example
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
loadbalancer:
enabled: true
circuitbreaker:
enabled: true
logging:
level:
root: info
com.tencent.cloud: debug
management:
endpoints:
web:
exposure:
include:
- polaris-circuit-breaker

@ -1,77 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-circuitbreaker-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-webclient-example</artifactId>
<name>Polaris Circuit Breaker WebClient Example</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-circuitbreaker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,59 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.webclient.example;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Circuit breaker example caller controller.
*
* @author sean yu
*/
@RestController
@RequestMapping("/example/service/a")
public class ServiceAController {
@Autowired
private ReactiveCircuitBreakerFactory reactiveCircuitBreakerFactory;
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping("/getBServiceInfo")
public Mono<String> getBServiceInfo() {
return webClientBuilder
.build()
.get()
.uri("/example/service/b/info")
.retrieve()
.bodyToMono(String.class)
.transform(it ->
reactiveCircuitBreakerFactory
.create("polaris-circuitbreaker-callee-service#/example/service/b/info")
.run(it, throwable -> Mono.just("fallback: trigger the refuse for service b"))
);
}
}

@ -1,45 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.circuitbreaker.webclient.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Circuit breaker example caller application.
*
* @author sean yu
*/
@SpringBootApplication
public class ServiceAWebClient {
public static void main(String[] args) {
SpringApplication.run(ServiceAWebClient.class, args);
}
@LoadBalanced
@Bean
WebClient.Builder webClientBuilder() {
return WebClient.builder()
.baseUrl("http://polaris-circuitbreaker-callee-service");
}
}

@ -1,26 +0,0 @@
server:
port: 48080
spring:
application:
name: polaris-circuitbreaker-webclient-example
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
loadbalancer:
enabled: true
circuitbreaker:
enabled: true
logging:
level:
root: info
com.tencent.cloud: debug
management:
endpoints:
web:
exposure:
include:
- polaris-circuit-breaker

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-circuitbreaker-example</artifactId>
<name>Polaris Circuit Breaker Example</name>
<packaging>pom</packaging>
<modules>
<module>polaris-circuitbreaker-feign-example</module>
<module>polaris-circuitbreaker-gateway-example</module>
<module>polaris-circuitbreaker-resttemplate-example</module>
<module>polaris-circuitbreaker-webclient-example</module>
<module>polaris-circuitbreaker-callee-service</module>
<module>polaris-circuitbreaker-callee-service2</module>
</modules>
</project>

@ -1,77 +0,0 @@
# Polaris Config Example 使用指南
## 1. bootstrap.yml 配置
修改 resources/bootstrap.yml ```spring.cloud.polaris.config.address``` 北极星服务端地址。
> 注意是在 bootstrap.yml 里配置,而不是在 application.yml 里配置。因为配置中心相关的配置是在 bootstrap 阶段依赖的配置。
```` yaml
spring:
application:
name: polaris-config-example
cloud:
polaris:
namespace: dev
config:
address: grpc://127.0.0.1:8093 # the address of polaris config server
auto-refresh: true # auto refresh when config file changed
groups:
- name: ${spring.application.name} # group name
files: [ "config/application.properties", "config/bootstrap.yml" ] # config/application.properties takes precedence over config/bootstrap.yml
````
## 2. 在北极星服务端创建配置文件
### 2.1 创建 namespace dev
### 2.2 创建配置文件分组polaris-config-example
北极星的配置文件分组概念为一组配置文件的集合,推荐应用名=分组名,例如在我们的示例中,新建一个 polaris-config-example 的分组。
把 polaris-config-example 应用的配置文件都放在 polaris-config-example 分组下,这样便于配置管理。
### 2.3 创建两个配置文件 config/application.properties 、config/bootstrap.yml
北极星配置中心的控制台,配置文件名可以通过 / 来按树状目录结构展示,通过树状结构可以清晰的管理配置文件。
#### 2.3.1 config/application.properties 文件内容
```` properties
timeout = 3000
````
#### 2.3.2 config/bootstrap.yml 文件内容
````yaml
teacher:
name : 张三
age: 38
````
页面样例如下图所示:
![](polaris-config-ui.png)
## 3. 运行 PolarisConfigExampleApplication
## 4. 访问接口
````
curl "http://localhost:48084/timeout"
curl "http://localhost:48084/person"
````
## 5. 动态推送能力
### 5.1 管控台动态修改并发布 config/application.properties
```` properties
timeout = 5000
````
### 5.2 再次访问接口
````
curl "http://localhost:48084/timeout"
````

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

@ -1,68 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-config-example</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Cloud Tencent dependency -->
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,52 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.config.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* the endpoint for get config.
*
* @author lepdou 2022-03-10
*/
@RestController
public class ConfigController {
@Value("${timeout:1000}")
private int timeout;
@Autowired
private Person person;
@Autowired
private Environment environment;
@GetMapping("/timeout")
public int timeout() {
environment.getProperty("timeout", "1000");
return timeout;
}
@GetMapping("/person")
public String person() {
return person.toString();
}
}

@ -1,68 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.config.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* example property object.
*
* @author lepdou 2022-03-28
*/
@Component
@ConfigurationProperties(prefix = "teacher")
public class Person {
private String name;
private int age;
private boolean isDirector;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isDirector() {
return isDirector;
}
public void setIsDirector(boolean isDirector) {
this.isDirector = isDirector;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", age=" + age + ", isDirector=" + isDirector + '\'' + '}';
}
}

@ -1,66 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.config.example;
import java.util.Set;
import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener;
import com.tencent.cloud.polaris.config.listener.ConfigChangeEvent;
import org.springframework.stereotype.Component;
/**
* Custom Config Listener Example .
*
* @author Palmer Xu 2022-06-06
*/
@Component
public final class PersonConfigChangeListener {
/**
* PolarisConfigKVFileChangeListener Example .
* @param event instance of {@link ConfigChangeEvent}
*/
@PolarisConfigKVFileChangeListener(interestedKeyPrefixes = "teacher")
public void onChange(ConfigChangeEvent event) {
Set<String> changedKeys = event.changedKeys();
for (String changedKey : changedKeys) {
System.out.printf("%s = %s , ThreadId: %s\n", changedKey, event.getChange(changedKey), Thread.currentThread().getId());
}
}
@PolarisConfigKVFileChangeListener(interestedKeyPrefixes = "teacher", async = false)
public void syncListen(ConfigChangeEvent event) {
Set<String> changedKeys = event.changedKeys();
for (String changedKey : changedKeys) {
System.out.printf("%s = %s , ThreadId: %s\n", changedKey, event.getChange(changedKey), Thread.currentThread().getId());
}
}
@PolarisConfigKVFileChangeListener(interestedKeyPrefixes = "teacher", async = false)
public void syncListen2(ConfigChangeEvent event) {
Set<String> changedKeys = event.changedKeys();
for (String changedKey : changedKeys) {
System.out.printf("%s = %s , ThreadId: %s\n", changedKey, event.getChange(changedKey), Thread.currentThread().getId());
}
}
}

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.config.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* example application starter.
*
* @author lepdou 2022-03-10
*/
@SpringBootApplication
public class PolarisConfigExampleApplication {
public static void main(String[] args) {
SpringApplication.run(PolarisConfigExampleApplication.class, args);
}
}

@ -1,24 +0,0 @@
server:
port: 48084
spring:
application:
name: polaris-config-example
profiles:
active: abc
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
config:
auto-refresh: true # auto refresh when config file changed
# data-source: local # config data source default is polaris.
# local-file-root-path: # set root path for reading config file, when in local data source
groups:
- name: ${spring.application.name} # group name
files: [ "config/application.properties", "config/bootstrap.yml" ] # config/application.properties takes precedence over config/bootstrap.yml
management:
endpoints:
web:
exposure:
include:
- polaris-config

@ -1,67 +0,0 @@
# Spring Cloud Polaris Discovery example
## 样例简介
本样例将介绍如何在Spring Cloud项目中使用```spring-cloud-starter-tencent-polaris-discovery```以使用其各项功能。
该样例分为两个微服务,即 ```discovery-caller-service``` 和 ```discovery-callee-service ```。
其中 ```discovery-caller-service``` 调用 ```discovery-callee-service```
## 使用说明
### 修改配置
修改 resource/bootstrap.yml 中北极星的服务端地址
```yaml
spring:
cloud:
polaris:
address: grpc://${ip}:8091
```
### 启动样例
#### 启动Polaris后端服务
参考[Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)。
#### 启动应用
- IDEA启动
分别启动
1. ```spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service```下的```DiscoveryCallerService```
2. ```spring-cloud-tencent-examples/polaris-discovery-example/discovery-callee-service```下的```DiscoveryCalleeService```
### 验证
#### 调用 discovery-caller-service 暴露的接口
执行以下命令发起Feign调用其逻辑为```DiscoveryCalleeService```返回 value1+value2 的和
```shell
curl -L -X GET 'http://localhost:48080/discovery/service/caller/feign?value1=1&value2=2'
```
预期返回值
```
3
```
#### RestTemplate调用
执行以下命令发起RestTemplate调用其逻辑为```DiscoveryCalleeService```返回一段字符串
```shell
curl -L -X GET 'http://localhost:48080/discovery/service/caller/rest'
```
预期返回值
```
Discovery Service Callee
```

@ -1,81 +0,0 @@
# Spring Cloud Polaris Discovery example
## Example Introduction
This example shows how to use ```spring-cloud-starter-tencent-polaris-discovery`` in Spring Cloud project for its features.
This example is divided to two microservice, discovery-caller-service and discovery-callee-service. In these two microservices, discovery-caller-service invokes discovery-callee-service.
## Instruction
### Configuration
The configuration is as the following shows. ${ip} and ${port} are Polaris backend IP address and port number.
```yaml
spring:
application:
name: ${application.name}
cloud:
polaris:
address: ${ip}:${port}
```
### Launching Example
#### Launching Polaris Backend Service
Reference to [Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)
#### Launching Application
- IDEA Launching
Launching ```spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service```'s ```DiscoveryCallerService``` and ```spring-cloud-tencent-examples/polaris-discovery-example/discovery-callee-service```'s ```DiscoveryCalleeService```
- Maven Package Launching
Execute under ```spring-cloud-tencent-examples/polaris-discovery-example```
```sh
mvn clean package
```
Then at ```discovery-caller-service``` and ```discovery-callee-service``` find the package that generates jar, and run it
```
java -jar ${app.jar}
```
Launch application, change ${app.jar} to jar's package name
### Verify
#### Feign Invoke
Execute the following orders to invoke Feign, ```DiscoveryCalleeService``` goes bank to the sum of value1+value2
```shell
curl -L -X GET 'http://localhost:48080/discovery/service/caller/feign?value1=1&value2=2'
```
Expected return rate
```
3
```
#### RestTemplate Invoke
Execute the following orders to invoke RestTemplate, ```DiscoveryCalleeService``` goes back to string characters
```shell
curl -L -X GET 'http://localhost:48080/discovery/service/caller/rest'
```
Expected return rate
```
Discovery Service Callee
```

@ -1,76 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-discovery-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>discovery-callee-service</artifactId>
<name>Polaris Discovery Callee Service</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-contract</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.tencent.polaris</groupId>-->
<!-- <artifactId>connector-consul</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.tencent.polaris</groupId>-->
<!-- <artifactId>connector-nacos</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,47 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.discovery.service.callee;
import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.springframework.stereotype.Component;
/**
* custom metadata for instance.
*
* @author lepdou 2022-06-16
*/
@Component
public class CustomMetadata implements InstanceMetadataProvider {
@Override
public Map<String, String> getMetadata() {
Map<String, String> metadata = new HashMap<>();
metadata.put("k1", "v1");
return metadata;
}
@Override
public String getZone() {
return "shanghai-zone-1";
}
}

@ -1,69 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.callee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Discovery callee controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/discovery/service/callee")
public class DiscoveryCalleeController {
private static final Logger LOG = LoggerFactory.getLogger(DiscoveryCalleeController.class);
@Value("${server.port:0}")
private int port;
@Value("${spring.cloud.client.ip-address:127.0.0.1}")
private String ip;
/**
* Get information of callee.
*
* @return information of callee
*/
@GetMapping("/info")
public String info() {
LOG.info("Discovery Service Callee [{}:{}] is called.", ip, port);
return String.format("Discovery Service Callee [%s:%s] is called.", ip, port);
}
/**
* Get sum of two value.
*
* @param value1 value 1
* @param value2 value 2
* @return sum
*/
@GetMapping("/sum")
public int sum(@RequestParam int value1, @RequestParam int value2) {
LOG.info("Discovery Service Callee [{}:{}] is called and sum is {}.", ip, port, value1 + value2);
return value1 + value2;
}
}

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.callee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Discovery callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class DiscoveryCalleeService {
public static void main(String[] args) {
SpringApplication.run(DiscoveryCalleeService.class, args);
}
}

@ -1,53 +0,0 @@
server:
port: ${random.int(7003,7005)}
spring:
application:
name: DiscoveryCalleeService
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
discovery:
enabled: true
register: true
contract:
exposure: true
stat:
enabled: true
port: 28082
# pushgateway:
# enabled: true
# address: 127.0.0.1:9091
tencent:
metadata:
content:
region: shanghai
rpc-enhancement:
reporter:
enabled: true
# consul:
# port: 8500
# host: 127.0.0.1
# enabled: true
# discovery:
# enabled: true
# register: true
# instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
# service-name: ${spring.application.name}
# ip-address: localhost
# prefer-ip-address: true
# nacos:
# enabled: true
# password: nacos
# username: nacos
# discovery:
# enabled: true
# register-enabled: true
# group: polaris
# server-addr: 127.0.0.1:8848
#eureka:
# client:
# serviceUrl:
# defaultZone: http://127.0.0.1:7654/eureka/

@ -1,76 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-discovery-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>discovery-caller-service</artifactId>
<name>Polaris Discovery Caller Service</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-contract</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.retry</groupId>-->
<!-- <artifactId>spring-retry</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.tencent.polaris</groupId>-->
<!-- <artifactId>connector-consul</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.tencent.polaris</groupId>-->
<!-- <artifactId>connector-nacos</artifactId>-->
<!-- </dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,40 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.caller;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Discovery callee feign client.
*
* @author Haotian Zhang
*/
@FeignClient(value = "DiscoveryCalleeService", fallback = DiscoveryCalleeServiceFallback.class)
public interface DiscoveryCalleeService {
/**
* Get sum of two value.
* @param value1 value 1
* @param value2 value 2
* @return sum
*/
@GetMapping("/discovery/service/callee/sum")
int sum(@RequestParam("value1") int value1, @RequestParam("value2") int value2);
}

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.caller;
import org.springframework.stereotype.Component;
/**
* Discovery callee feign client fallback.
*
* @author Haotian Zhang
*/
@Component
public class DiscoveryCalleeServiceFallback implements DiscoveryCalleeService {
@Override
public int sum(int value1, int value2) {
return 0;
}
}

@ -1,70 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.caller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Discovery caller controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/discovery/service/caller")
public class DiscoveryCallerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryCalleeService discoveryCalleeService;
/**
* Get sum of two value.
* @param value1 value 1
* @param value2 value 2
* @return sum
*/
@RequestMapping("/feign")
public int feign(@RequestParam int value1, @RequestParam int value2) {
return discoveryCalleeService.sum(value1, value2);
}
/**
* Get information of callee.
* @return information of callee
*/
@GetMapping("/rest")
public String rest() {
return restTemplate.getForObject("http://DiscoveryCalleeService/discovery/service/callee/info", String.class);
}
/**
* health check.
* @return health check info
*/
@GetMapping("/healthCheck")
public String healthCheck() {
return "pk ok";
}
}

@ -1,47 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery.service.caller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* Discovery caller application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DiscoveryCallerService {
public static void main(String[] args) {
SpringApplication.run(DiscoveryCallerService.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

@ -1,68 +0,0 @@
server:
session-timeout: 1800
port: 48080
spring:
application:
name: DiscoveryCallerService
cloud:
tencent:
metadata:
content:
region: shanghai
rpc-enhancement:
reporter:
enabled: true
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
discovery:
enabled: true
register: true
heartbeat:
enabled: true
health-check-url: /discovery/service/caller/healthCheck
contract:
exposure: true
report:
enabled: true
stat:
enabled: true
port: 28081
# pushgateway:
# enabled: true
# address: 127.0.0.1:9091
# consul:
# port: 8500
# host: 127.0.0.1
# enabled: true
# discovery:
# enabled: true
# register: true
# health-check-path: /actuator/health
# health-check-interval: 10s
# instance-id: ${spring.application.name}:${server.port}
# service-name: ${spring.application.name}
# ip-address: localhost
# prefer-ip-address: true
# nacos:
# enabled: true
# password: nacos
# username: nacos
# context-path: /nacos
# discovery:
# enabled: true
# register-enabled: true
# group: polaris
# server-addr: 127.0.0.1:8848
# cluster-name: polaris
#eureka:
# client:
# serviceUrl:
# defaultZone: http://127.0.0.1:7654/eureka/
management:
endpoints:
web:
exposure:
include:
- polaris-discovery

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-discovery-example</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Starter Tencent Polaris Discovery Example</name>
<modules>
<module>discovery-callee-service</module>
<module>discovery-caller-service</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-bootstrap</artifactId>
</dependency>
</dependencies>
</project>

@ -1,68 +0,0 @@
# Spring Cloud Polaris Gateway example
## 样例简介
本样例将介绍如何在Spring Cloud项目中使用```spring-cloud-tencent-polaris-gateway```以使用其各项功能。
本样例包括 ```gateway-scg-service```和```gateway-callee-service```。```gateway-scg-service```调用```gateway-callee-service```。
## 使用说明
### 修改配置
配置如下所示。其中,${ip}和${port}为Polaris后端服务的IP地址与端口号。
```yaml
spring:
application:
name: ${application.name}
cloud:
polaris:
address: ${ip}:${port}
```
### 启动样例
#### 启动Polaris后端服务
参考[Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)。
#### 启动应用
- IDEA启动
分别启动```spring-cloud-tencent-examples/polaris-gateway-example/gateway-scg-service```的```GatewayScgService```和```spring-cloud-tencent-examples/polaris-gateway-example/gateway-callee-service```的```GatewayCalleeService```
- Maven打包启动
在```spring-cloud-tencent-examples/polaris-gateway-example```下执行
```sh
mvn clean package
```
然后在 ```gateway-scg-service```和```gateway-callee-service```下找到生成的jar包运行
```
java -jar ${app.jar}
```
启动应用,其中${app.jar}替换为对应的jar包名。
### 验证
#### Spring-Cloud-Gateway调用
```shell
curl -L -X GET 'http://localhost:48083/GatewayCalleeService/gateway/example/callee/echo' -H 'SCT-CUSTOM-METADATA: {"b": 2}'
```
预期返回值
```
{"a":"1","b":2}
```
#### 网关限流
参考[Polaris RateLimit Example](../polaris-ratelimit-example/README-zh.md)

@ -1,69 +0,0 @@
# Spring Cloud Polaris Gateway example
## Example Introduction
This example shows how to use ```spring-cloud-tencent-polaris-gateway``` in Spring Cloud project for its features.
This example contains ```gateway-scg-service``` and ```gateway-callee-service```. ```gateway-scg-service``` invoke ```gateway-callee-service```.
## Instruction
### Configuration
The configuration is as the following shows. ${ip} and ${port} are Polaris backend IP address and port number.
```yaml
spring:
application:
name: ${application.name}
cloud:
polaris:
address: ${ip}:${port}
```
### Launching Example
#### Launching Polaris Backend Service
Reference to [Polaris Getting Started](https://github.com/PolarisMesh/polaris#getting-started)
#### Launching Application
- IDEA Launching
Launching ```spring-cloud-tencent-examples/polaris-gateway-example/gateway-scg-service```'s ```GatewayScgService``` and ```spring-cloud-tencent-examples/polaris-gateway-example/gateway-callee-service```'s ```GatewayCalleeService```
- Maven Package Launching
Execute under ```spring-cloud-tencent-examples/polaris-gateway-example```
```sh
mvn clean package
```
Then find the jars under ```gateway-scg-service``` and ```gateway-callee-service```, and run it:
```
java -jar ${app.jar}
```
Launch application, change ${app.jar} to jar's package name.
### Verify
#### Spring-Cloud-Gateway Invoke
```shell
curl -L -X GET 'http://localhost:48083/GatewayCalleeService/gateway/example/callee/echo' -H 'SCT-CUSTOM-METADATA: {"b": 2}'
```
Expected return rate
```
{"a":"1","b":2}
```
#### Gateway Rate Limit
See [Polaris RateLimit Example](../polaris-ratelimit-example/README.md)

@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-gateway-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-callee-service</artifactId>
<name>Spring Cloud Starter Tencent Polaris Gateway Callee Example</name>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-metadata-transfer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.gateway.example.callee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Gateway callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class GatewayCalleeApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayCalleeApplication.class, args);
}
}

@ -1,72 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Gateway callee controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/gateway/example/callee")
public class GatewayCalleeController {
private static Logger LOG = LoggerFactory.getLogger(GatewayCalleeController.class);
@Value("${server.port:0}")
private int port;
/**
* Get information of callee.
* @return information of callee
*/
@RequestMapping("/info")
public String info() {
LOG.info("Gateway Example Callee [{}] is called.", port);
return String.format("Gateway Example Callee [%s] is called.", port);
}
/**
* Get metadata in HTTP header.
*
* @param metadataStr metadata string
* @return metadata in HTTP header
* @throws UnsupportedEncodingException encoding exception
*/
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, UTF_8));
metadataStr = URLDecoder.decode(metadataStr, UTF_8);
return metadataStr;
}
}

@ -1,14 +0,0 @@
server:
session-timeout: 1800
port: 48081
spring:
application:
name: GatewayCalleeService
cloud:
tencent:
metadata:
content:
env: blue
polaris:
address: grpc://119.91.66.223:8091
namespace: default

@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-gateway-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-callee-service2</artifactId>
<name>Spring Cloud Starter Tencent Polaris Gateway Callee Example</name>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-metadata-transfer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.gateway.example.callee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Gateway callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class GatewayCalleeApplication2 {
public static void main(String[] args) {
SpringApplication.run(GatewayCalleeApplication2.class, args);
}
}

@ -1,72 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Gateway callee controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/gateway/example/callee")
public class GatewayCalleeController {
private static Logger LOG = LoggerFactory.getLogger(GatewayCalleeController.class);
@Value("${server.port:0}")
private int port;
/**
* Get information of callee.
* @return information of callee
*/
@RequestMapping("/info")
public String info() {
LOG.info("Gateway Example Callee [{}] is called.", port);
return String.format("Gateway Example Callee [%s] is called.", port);
}
/**
* Get metadata in HTTP header.
*
* @param metadataStr metadata string
* @return metadata in HTTP header
* @throws UnsupportedEncodingException encoding exception
*/
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, UTF_8));
metadataStr = URLDecoder.decode(metadataStr, UTF_8);
return metadataStr;
}
}

@ -1,14 +0,0 @@
server:
session-timeout: 1800
port: 48082
spring:
application:
name: GatewayCalleeService
cloud:
tencent:
metadata:
content:
env: green
polaris:
address: grpc://119.91.66.223:8091
namespace: default

@ -1,52 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-gateway-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-scg-service</artifactId>
<name>Spring Cloud Starter Tencent Polaris Gateway SCG Example</name>
<dependencies>
<dependency>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
<groupId>com.tencent.cloud</groupId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-router</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-gateway-plugin</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-metadata-transfer</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-featureenv-plugin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
</project>

@ -1,34 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.gateway.example.scg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SCG application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class GatewayScgApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayScgApplication.class, args);
}
}

@ -1,68 +0,0 @@
server:
session-timeout: 1800
port: 48083
spring:
application:
name: GatewayScgService
cloud:
tencent:
plugin:
scg:
staining:
enabled: true
rule-staining:
enabled: true
router:
feature-env:
enabled: true
metadata:
content:
a: 1
transitive:
- a
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
gateway:
discovery:
locator:
enabled: true
'predicates[0]':
name: Path
args:
patterns: '''/'' + serviceId + ''/**'''
'filters[0]':
name: RewritePath
args:
regexp: '''/'' + serviceId + ''/(?<remaining>.*)'''
replacement: '''/$\{remaining}'''
'filters[1]':
name: Retry
args:
retries: 3
exceptions:
'[0]': '''java.net.ConnectException'''
'[1]': '''java.io.IOException'''
statuses:
'[0]': '''BAD_GATEWAY'''
'[1]': '''SERVICE_UNAVAILABLE'''
series:
'[0]': '''CLIENT_ERROR'''
methods:
'[0]': '''GET'''
'[1]': '''POST'''
'[2]': '''PUT'''
'[3]': '''DELETE'''
backoff:
firstBackoff: '''100ms'''
maxBackoff: '''500ms'''
factor: 2
basedOnPreviousValue: false
routes:
- id: GatewayCalleeService
uri: lb://GatewayCalleeService
predicates:
- Path=/GatewayCalleeService/**
filters:
- StripPrefix=1

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-gateway-example</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Starter Tencent Polaris Gateway Example</name>
<modules>
<module>gateway-scg-service</module>
<module>gateway-callee-service</module>
<module>gateway-callee-service2</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,62 +0,0 @@
# Spring Cloud Polaris RateLimit Example
## 项目说明
本项目演示如何使用 Polaris ratelimit starter 完成 Spring Cloud 应用的限流管理。
## 示例
### 如何接入
在启动示例进行演示之前,我们先了解一下如何接入 Polaris 限流组件。
> **注意:本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。**
1. 首先,修改 `pom.xml` 文件,引入 Polaris ratelimit starter。
```xml
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>
</dependency>
```
2. 启动应用
北极星提供的example都支持在IDE中直接运行或者编译打包后通过命令行方式进行运行。
- 在本地启动Polaris服务端。
- 在北极星服务端可以通过控制台在命名空间Production下添加服务RateLimitCalleeService。
- 启动服务被调方:
1. IDE直接启动找到主类 `RateLimitCalleeService`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar ratelimit-callee-sevice-${verion}.jar`启动应用。
- 启动后,可以在北极星控制台上看到注册上来的服务实例信息。
3. 调用服务
通过浏览器访问http://127.0.0.1:48081/business/invoke可以看到以下输出信息
````
hello world for ratelimit service 1
hello world for ratelimit service 2
hello world for ratelimit service 3
...
````
4. 配置限流规则并验证
北极星提供了三个方式进行限流规则的配置控制台、HTTP接口以及本地文件
- 使用的方式为通过HTTP接口进行配置。通过以下命令来配置
````
curl -X POST -H "Content-Type:application/json" 127.0.0.1:8090/naming/v1/ratelimits -d @rule.json
````
- 通过控制台进行配置,示例如下:
![](polaris-ratelimit-ui.png)
5. 验证限流效果
继续访问http://127.0.0.1:48081/business/invoke可以看到10次调用后就开始被限流
````
hello world for ratelimit service 1
hello world for ratelimit service 2
...
hello world for ratelimit service 10
request has been limited, service is RateLimitCalleeService, path is /business/invoke, 11
````

@ -1,70 +0,0 @@
# Spring Cloud Polaris RateLimit Example
## Project Explanation
This project shows how to use ratelimit feature of Polaris to complete Spring Cloud application's rate limit
## Example
### How to access
Before showcasing the project, let's get to know how to access Polaris rate limit component
> ** note: this chapter is to help you understand different ways to access, the codes in the example has been executed, you don't need to re-edit.**
1, first, change document `pom.xml`, introduce Polaris ratelimit starter
```xml
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>
</dependency>
```
2. Launch Application
Examples provided by Polaris all support to run at IDE, or compile and run with orders
- Launch Polaris locally
- at Polaris end, through control panel, under namespace Product, add RateLimitCalleeService
- Launch callee server:
1. Launch IDE directly: First find `RateLimitCalleeService`, execute main then launch application
2. compile package then launch: first execute `mvn clean package` compile the package, then execute `java -jar ratelimit-callee-sevice-${verion}.jar` execute the application
- After launching, one can watch server instance from Polaris control panel
3. Invoke Service
After visiting http://127.0.0.1:48081/business/invoke, one can see the following information:
````
hello world for ratelimit service 1
hello world for ratelimit service 2
hello world for ratelimit service 3
...
````
4. Configuration rate limit and verification
Polaris provide three wats to conduct rate limit configuration (control panel, HTTP port and local files)
- HTTP configuration. One can figure with the following steps:
````
curl -X POST -H "Content-Type:application/json" 127.0.0.1:8090/naming/v1/ratelimits -d @rule.json
````
- Configuration is done through the console, example as follows.
![](polaris-ratelimit-ui.png)
5. Verify rate limit result
continue visit http://127.0.0.1:48081/business/invoke, one can see, after 10 invokes, rate limit will start:
````
hello world for ratelimit service 1
hello world for ratelimit service 2
````

Binary file not shown.

Before

Width:  |  Height:  |  Size: 384 KiB

@ -1,27 +0,0 @@
<?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">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-ratelimit-example</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Starter Tencent Polaris RateLimit Example</name>
<modules>
<module>ratelimit-callee-service</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
</project>

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-ratelimit-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ratelimit-callee-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,176 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.ratelimit.example.service.callee;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException.TooManyRequests;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
/**
* Rate limit controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/business")
public class BusinessController {
private static final Logger LOG = LoggerFactory.getLogger(BusinessController.class);
private final AtomicInteger index = new AtomicInteger(0);
private final AtomicLong lastTimestamp = new AtomicLong(0);
@Autowired
private RestTemplate restTemplate;
@Autowired
private WebClient.Builder webClientBuilder;
@Value("${spring.application.name}")
private String appName;
/**
* Get information.
* @return information
*/
@GetMapping("/info")
public String info() {
return "hello world for ratelimit service " + index.incrementAndGet();
}
@GetMapping("/info/webclient")
public Mono<String> infoWebClient() {
return Mono.just("hello world for ratelimit service " + index.incrementAndGet());
}
@GetMapping("/invoke/webclient")
public String invokeInfoWebClient() throws InterruptedException, ExecutionException {
StringBuffer builder = new StringBuffer();
WebClient webClient = webClientBuilder.baseUrl("http://" + appName).build();
List<Mono<String>> monoList = new ArrayList<>();
for (int i = 0; i < 30; i++) {
Mono<String> response = webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/business/info/webclient")
.queryParam("yyy", "yyy")
.build()
)
.header("xxx", "xxx")
.retrieve()
.bodyToMono(String.class)
.doOnSuccess(s -> builder.append(s + "\n"))
.doOnError(e -> {
if (e instanceof WebClientResponseException) {
if (((WebClientResponseException) e).getRawStatusCode() == 429) {
builder.append("TooManyRequests ").append(index.incrementAndGet() + "\n");
}
}
})
.onErrorReturn("");
monoList.add(response);
}
for (Mono<String> mono : monoList) {
mono.toFuture().get();
}
index.set(0);
return builder.toString();
}
/**
* Get information 30 times per 1 second.
*
* @return result of 30 calls.
* @throws InterruptedException exception
*/
@GetMapping("/invoke")
public String invokeInfo() throws InterruptedException {
StringBuffer builder = new StringBuffer();
CountDownLatch count = new CountDownLatch(30);
for (int i = 0; i < 30; i++) {
new Thread(() -> {
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("xxx", "xxx");
ResponseEntity<String> entity = restTemplate.exchange(
"http://" + appName + "/business/info?yyy={yyy}",
HttpMethod.GET,
new HttpEntity<>(httpHeaders),
String.class,
"yyy"
);
builder.append(entity.getBody() + "\n");
}
catch (RestClientException e) {
if (e instanceof TooManyRequests) {
builder.append("TooManyRequests ").append(index.incrementAndGet() + "\n");
}
else {
throw e;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
count.countDown();
}
}).start();
}
count.await();
index.set(0);
return builder.toString();
}
/**
* Get information with unirate.
*
* @return information
*/
@GetMapping("/unirate")
public String unirate() {
long currentTimestamp = System.currentTimeMillis();
long lastTime = lastTimestamp.get();
if (lastTime != 0) {
LOG.info("Current timestamp:" + currentTimestamp + ", diff from last timestamp:" + (currentTimestamp - lastTime));
}
else {
LOG.info("Current timestamp:" + currentTimestamp);
}
lastTimestamp.set(currentTimestamp);
return "hello world for ratelimit service with diff from last request:" + (currentTimestamp - lastTime) + "ms.";
}
}

@ -1,51 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.ratelimit.example.service.callee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Rate limit application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class RateLimitCalleeService {
public static void main(String[] args) {
SpringApplication.run(RateLimitCalleeService.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@LoadBalanced
@Bean
WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}

@ -1,26 +0,0 @@
server:
port: 48081
spring:
application:
name: RateLimitCalleeService
cloud:
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
ratelimit:
enabled: true
rejectRequestTipsFilePath: reject-tips.html
maxQueuingTime: 500
stat:
enabled: true
port: 28083
management:
endpoints:
web:
exposure:
include:
- polaris-ratelimit
logging:
level:
com.tencent.cloud.polaris: debug

@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>polaris-router-example</artifactId>
<packaging>pom</packaging>
<modules>
<module>router-callee-service1</module>
<module>router-callee-service2</module>
<module>router-caller-service</module>
</modules>
</project>

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-router-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>router-callee-service1</artifactId>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,35 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Router callee application.
*
* @author lepdou 2022-04-06
*/
@SpringBootApplication
public class RouterCalleeApplication1 {
public static void main(String[] args) {
SpringApplication.run(RouterCalleeApplication1.class, args);
}
}

@ -1,53 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Discovery callee controller.
*
* @author lepdou 2022-04-06
*/
@RestController
@RequestMapping("/router/service/callee")
public class RouterCalleeController {
private static Logger LOG = LoggerFactory.getLogger(RouterCalleeController.class);
@Value("${server.port:0}")
private int port;
/**
* Get information of callee.
* @return information of callee
*/
@PostMapping("/info")
public String info(String name, @RequestBody User user) {
LOG.info("Discovery Service Callee [{}] is called.", port);
return String.format("Discovery Service Callee [%s] is called. user = %s", port, user);
}
}

@ -1,53 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
/**
* demo object.
* @author lepdou 2022-05-12
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

@ -1,14 +0,0 @@
server:
port: 48081
spring:
application:
name: RouterCalleeService
cloud:
tencent:
metadata:
content:
label1: value1
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-router-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>router-callee-service2</artifactId>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,35 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Router callee application.
*
* @author lepdou 2022-04-06
*/
@SpringBootApplication
public class RouterCalleeApplication2 {
public static void main(String[] args) {
SpringApplication.run(RouterCalleeApplication2.class, args);
}
}

@ -1,54 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Discovery callee controller.
*
* @author lepdou 2022-04-06
*/
@RestController
@RequestMapping("/router/service/callee")
public class RouterCalleeController {
private static Logger LOG = LoggerFactory.getLogger(RouterCalleeController.class);
@Value("${server.port:0}")
private int port;
/**
* Get information of callee.
* @return information of callee
*/
@PostMapping("/info")
public String info(@RequestParam("name") String name, @RequestBody User user) {
LOG.info("Discovery Service Callee [{}] is called.", port);
return String.format("Discovery Service Callee [%s] is called. user = %s", port, user);
}
}

@ -1,53 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
/**
* demo object.
* @author lepdou 2022-05-12
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

@ -1,14 +0,0 @@
server:
port: 48082
spring:
application:
name: RouterCalleeService
cloud:
tencent:
metadata:
content:
label1: value2
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true

@ -1,82 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>polaris-router-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>router-caller-service</artifactId>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-router</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,51 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.router.example;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.gson.Gson;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
/**
* Custom router label resolver for spring web request.
* @author lepdou 2022-07-20
*/
@Component
public class CustomSpringWebRouterLabelResolver implements SpringWebRouterLabelResolver {
private final Gson gson = new Gson();
@Override
public int getOrder() {
return 0;
}
@Override
public Map<String, String> resolve(HttpRequest request, byte[] body, Set<String> expressionLabelKeys) {
Map<String, String> labels = new HashMap<>();
User user = gson.fromJson(new String(body), User.class);
labels.put("user", user.getName());
return labels;
}
}

@ -1,36 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Router callee feign client.
*
* @author lepdou 2022-04-06
*/
@FeignClient("RouterCalleeService")
public interface RouterCalleeService {
@PostMapping("/router/service/callee/info")
String info(@RequestParam("name") String name, @RequestBody User user);
}

@ -1,48 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* Router caller application.
*
* @author lepdou 2022-04-06
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class RouterCallerApplication {
public static void main(String[] args) {
SpringApplication.run(RouterCallerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

@ -1,76 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Discovery caller controller.
*
* @author lepdou 2022-04-06
*/
@RestController
@RequestMapping("/router/service/caller")
public class RouterCallerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private RouterCalleeService routerCalleeService;
/**
* Get info of two value.
* @return info
*/
@GetMapping("/feign")
public String feign(@RequestParam String name) {
User user = new User();
user.setName(name);
user.setAge(18);
return routerCalleeService.info(name, user);
}
/**
* Get information of callee.
* @return information of callee
*/
@GetMapping("/rest")
public String rest(@RequestParam String name) {
User user = new User();
user.setName(name);
user.setAge(18);
return restTemplate.postForObject(
"http://RouterCalleeService/router/service/callee/info?name={name}", user, String.class, name);
}
/**
* health check.
* @return health check info
*/
@GetMapping("/healthCheck")
public String healthCheck() {
return "pk ok";
}
}

@ -1,45 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.example;
/**
* demo object.
* @author lepdou 2022-05-12
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

@ -1,28 +0,0 @@
server:
port: 48083
spring:
application:
name: RouterCallerService
cloud:
tencent:
metadata:
content:
k1: v1
rpc-enhancement:
reporter:
enabled: true
polaris:
address: grpc://119.91.66.223:8091
namespace: default
enabled: true
loadbalancer:
enabled: true
stat:
enabled: true
port: 28081
management:
endpoints:
web:
exposure:
include:
- polaris-router

@ -17,12 +17,6 @@
<modules>
<module>multiple-discovery-example</module>
<module>polaris-discovery-example</module>
<module>polaris-ratelimit-example</module>
<module>polaris-circuitbreaker-example</module>
<module>polaris-gateway-example</module>
<module>polaris-config-example</module>
<module>polaris-router-example</module>
<module>metadata-transfer-example</module>
<module>polaris-router-grayrelease-example</module>
<module>polaris-router-featureenv-example</module>

@ -23,6 +23,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>

@ -17,16 +17,24 @@
package com.tencent.cloud.quickstart.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.quickstart.callee.config.DataSourceProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Quickstart callee controller.
*
@ -41,7 +49,10 @@ public class QuickstartCalleeController {
@Value("${server.port:0}")
private int port;
@Value("${appName:Callee}")
@Value("${spring.cloud.client.ip-address:127.0.0.1}")
private String ip;
@Value("${appName:${spring.application.name}}")
private String appName;
@Autowired
@ -55,7 +66,7 @@ public class QuickstartCalleeController {
*/
@GetMapping("/sum")
public int sum(@RequestParam int value1, @RequestParam int value2) {
LOG.info("Quickstart Callee Service is called and sum is {}.", value1 + value2);
LOG.info("Quickstart Callee Service [{}:{}] is called and sum is [{}].", ip, port, value1 + value2);
return value1 + value2;
}
@ -65,8 +76,23 @@ public class QuickstartCalleeController {
*/
@GetMapping("/info")
public String info() {
LOG.info("Quickstart [{}] Service [{}] is called. datasource = {}", appName, port, dataSourceProperties);
return String.format("Quickstart [%s] Service [%s] is called. datasource = [%s]", appName, port, dataSourceProperties);
LOG.info("Quickstart [{}] Service [{}:{}] is called. datasource = [{}].", appName, ip, port, dataSourceProperties);
return String.format("Quickstart [%s] Service [%s:%s] is called. datasource = [%s].", appName, ip, port, dataSourceProperties);
}
/**
* Get metadata in HTTP header.
*
* @param metadataStr metadata string
* @return metadata in HTTP header
* @throws UnsupportedEncodingException encoding exception
*/
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, UTF_8));
metadataStr = URLDecoder.decode(metadataStr, UTF_8);
return metadataStr;
}
/**
@ -76,7 +102,7 @@ public class QuickstartCalleeController {
*/
@GetMapping("/circuitBreak")
public String circuitBreak() {
LOG.info("Quickstart Callee Service is called right.");
return "Quickstart Callee Service is called right.";
LOG.info("Quickstart Callee Service [{}:{}] is called right.", ip, port);
return String.format("Quickstart Callee Service [%s:%s] is called right.", ip, port);
}
}

@ -15,12 +15,14 @@
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.quickstart.callee;
package com.tencent.cloud.quickstart.callee.config;
import java.util.Set;
import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener;
import com.tencent.cloud.polaris.config.listener.ConfigChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ -32,6 +34,8 @@ import org.springframework.stereotype.Component;
@Component
public final class CustomConfigChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(CustomConfigChangeListener.class);
/**
* PolarisConfigKVFileChangeListener Example .
* @param event instance of {@link ConfigChangeEvent}
@ -41,8 +45,7 @@ public final class CustomConfigChangeListener {
Set<String> changedKeys = event.changedKeys();
for (String changedKey : changedKeys) {
System.out.printf("%s = %s \n", changedKey, event.getChange(changedKey));
LOG.info("{} = {}", changedKey, event.getChange(changedKey));
}
}
}

@ -15,7 +15,7 @@
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.quickstart.callee;
package com.tencent.cloud.quickstart.callee.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ -16,14 +16,17 @@
*
*/
package com.tencent.cloud.ratelimit.example.service.callee;
package com.tencent.cloud.quickstart.callee.ratelimit;
import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
@ -33,14 +36,27 @@ import org.springframework.stereotype.Component;
*/
@Component
public class CustomLabelResolver implements PolarisRateLimiterLabelServletResolver {
private static final Logger LOG = LoggerFactory.getLogger(CustomLabelResolver.class);
@Value("${label.key-value:}")
private String[] keyValues;
@Override
public Map<String, String> resolve(HttpServletRequest request) {
// rate limit by some request params. such as query params, headers ..
return getLabels(keyValues);
}
private Map<String, String> getLabels(String[] keyValues) {
Map<String, String> labels = new HashMap<>();
labels.put("user", "zhangsan");
for (String kv : keyValues) {
String key = kv.substring(0, kv.indexOf(":"));
String value = kv.substring(kv.indexOf(":") + 1);
labels.put(key, value);
}
LOG.info("Current labels:{}", labels);
return labels;
}
}

@ -11,6 +11,16 @@ spring:
discovery:
enabled: true
register: true
contract:
exposure: true
report:
enabled: false
stat:
enabled: true
port: 28083
# pushgateway:
# enabled: true
# address: 127.0.0.1:9091
config:
address: grpc://119.91.66.223:8093
auto-refresh: true
@ -19,8 +29,20 @@ spring:
files: [ "config/callee.properties" ]
ratelimit:
enabled: true
rejectRequestTipsFilePath: reject-tips.html
maxQueuingTime: 500
tencent:
metadata:
content:
label1: value1
region: huanan
management:
endpoints:
web:
exposure:
include:
- polaris-discovery
- polaris-ratelimit
- polaris-config
label:
key-value: user:zhangsan

@ -23,6 +23,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save