1. 程式人生 > 實用技巧 >Spring Cloud(六)使用Alibaba Sentinel

Spring Cloud(六)使用Alibaba Sentinel

1、搭建Dashboard

下載jar包 https://github.com/alibaba/Sentinel/releases/download/v1.8.0/sentinel-dashboard-1.8.0.jar

啟動:java -jar sentinel-dashboard-1.8.0.jar

登入:使用者名稱和密碼均為sentinel

2、建立一個maven工程並編輯pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.ralgond</groupId>
	<artifactId>ali-sentinel</artifactId>
	<version>0.0.1-SNAPSHOT</version>

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

	<dependencies>
		<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>

		<!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-sentinel -->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
			<version>2.2.3.RELEASE</version>
		</dependency>

	</dependencies>

	<properties>
		<start-class>com.github.raglond.ali.sentinel.SentinelApplication</start-class>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>

	</build>
</project>

3、在src/main/resources下面建立一個yml檔案application.yml

server:
  port: 8001
  
spring:
  application:
    name: ali-sentinel
    
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

management:
  endpoints:
    web:
      exposure:
        include: '*'

4、建立主類

package com.github.raglond.ali.sentinel;

@SpringBootApplication
@RestController
public class SentinelApplication {

	@RequestMapping(method=RequestMethod.GET, value="/testA")
	public String testA() {
		return "...testA";
	}

	@RequestMapping(method=RequestMethod.GET, value="/testB")
	public String testB() {
		return "...testB";
	}
	
	public static void main(String args[]) {
		SpringApplication.run(SentinelApplication.class, args);
	}
}

5、編譯打包執行

編譯打包:mvn clean package
執行:java -jar target\ali-sentinel-0.0.1-SNAPSHOT.jar

在瀏覽器上輸入http://localhost:8001/testA,便可以在dashboard上看到相關的統計資訊。