一、准备工作
需要启动Nacos和Sentinel。


二、服务提供者
(1)导入依赖
<?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>springcloud</artifactId>
        <groupId>com.buba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>provider-8101</artifactId>
    <dependencies>
        <!--        springboot启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        nacos 相关 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--        完善监控信息-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project> 
(2)application.yml配置文件
server:
  port: 8101
spring:
  application:
    name: provider
  cloud:
    # nocos注册中心
    nacos:
      discovery:
        server-addr: localhost:8848
management:
  endpoints:
    web:
      exposure:
        include: "*" 
(3)业务逻辑代码
package com.buba.springcloud.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
    @Value("${server.port}")
    private String serverPort;
    @GetMapping(value = "/provider/get/{id}")
    public String getPayment(@PathVariable("id") Integer id) {
        return "Nacos的注册中心的端口是:: " + serverPort + ",id是:" + id;
    }
}
 
(4)启动类
package com.buba.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Provider_8101 {
    public static void main(String[] args) {
        SpringApplication.run(Provider_8101.class, args);
    }
}
 
三、服务消费者
(1)导入依赖
<?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>springcloud</artifactId>
        <groupId>com.buba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>consumer-80</artifactId>
    <dependencies>
        <!--   Nacos     -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</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>
    </dependencies>
</project> 
(2)application.yml配置文件
server:
  port: 80
spring:
  application:
    name: consumer
  cloud:
    # nocos注册中心
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        # 配置Sentinel Dashboard地址
        dashboard: 127.0.0.1:8080
        # 默认8719端口,假设被占用会自动从8719开始依次加1扫描,直到找到没有被占用的端口
        port: 8719
      # 取消懒加载
      eager: true
management:
  endpoints:
    web:
      exposure:
        include: '*' 
(3)业务逻辑代码
package com.buba.springcloud.util;
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class ExceptionUtils {
    public static String handleBlock(Integer id, BlockException ex) {
        return "熔断降级";
    }
    public static String handleFallback(Integer id, Throwable tx) {
        return "异常降级";
    }
} 
package com.buba.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class SpringConfig {
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
} 
package com.buba.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.buba.springcloud.util.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class HelloController {
    private RestTemplate restTemplate;
    @GetMapping(value = "/order/{id}")
    @SentinelResource(blockHandlerClass = ExceptionUtils.class, blockHandler = "handleBlock", fallbackClass = ExceptionUtils.class, fallback = "handleFallback")
    public String order(@PathVariable(value = "id") Integer id) {
        if (4 == id) {
            throw new IllegalArgumentException("非法参数异常");
        }
        return this.restTemplate.getForObject("http://provider" + "/provider/get/" + id, String.class);
    }
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}
 
(4)启动类
package com.buba.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Consumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(Consumer_80.class, args);
    }
}
 
(5)启动测试
![]()
![]()
                  
                  
                  
                  
                            
本文详细介绍了如何在Spring Cloud中整合Nacos作为服务注册中心,并结合Sentinel实现服务熔断与降级。通过创建服务提供者和消费者实例,展示了配置和代码实现步骤,以及如何使用Sentinel处理异常情况。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
                    
              
            
                  
					1万+
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
					
					
					


            