springcloud Alibaba--nacos作为服务注册中心

在上一篇博客中介绍了nacos作为分配配置中心传送门。本篇将nacos作为服务注册中进行介绍
前提条件是你可以连上nacos服务。操作步骤建nacos官方入门手册

服务发现
1.添加maven依赖

 <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>

注意一点:选择nacos的版本需要根据你的springboot版本号来决定

更多的详细的版本对应关系查看官网传送门
2.在 bootstrap.properties 或者 bootstrap.yml中配置 Nacos server 的地址和应用名
bootstrap.properties 中添加

spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

spring.application.name=example

bootstrap.yml 添加

spring:
  application:
    name: nacos-config-example
  profiles:
    active: test
  cloud:
    nacos:
      discovery:
        server-addr: http://127.0.0.1:8848

3.在启动类中通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能:

@EnableDiscoveryClient
@SpringBootApplication
public class DemoApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
    }

}
package com.example.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sz
 * @version V1.0
 * @Description: 测试nacos作为分布式配置中心(用一句话描述该文件做什么)
 * @date 2020-11-18
 */
@RefreshScope
@RestController
public class TestController {
    
    

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    int age;

    @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
    public String echo(@PathVariable String string) {
    
    
        System.out.println("请求进来了");
        return "Hello Nacos Discovery " + string;
    }




    @RequestMapping("/user")
    public String simple() {
    
    
        return "Hello Nacos Config!" + "Hello " + userName + " " + age + " [UserConfig]: ";

    }

   // @SentinelResource("resource")
    @RequestMapping("/test")
    public String test() {
    
    
        return "test";
    }
    @SentinelResource("resource")
    @RequestMapping("/hello")
    public String hello() {
    
    
        return "Hello";
    }
    public static void main(String[] args) {
    
    
        long startTime = System.currentTimeMillis();
        int i=0;
       initFlowRules();
        while (true) {
    
    
            Entry entry = null;
            try {
    
    
                i++;
                entry = SphU.entry("HelloWorld");
                /*您的业务逻辑 - 开始*/
                System.out.println("hello world");
                long tmp = System.currentTimeMillis();
                if (tmp-startTime >1000){
    
    
                    System.out.println("执行了"+i+"次");
                    break;
                }
                /*您的业务逻辑 - 结束*/
            } catch (BlockException e1) {
    
    
                /*流控逻辑处理 - 开始*/
                System.out.println("block!");
                /*流控逻辑处理 - 结束*/
            } finally {
    
    
                if (entry != null) {
    
    
                    entry.exit();
                }
            }
        }


    }



    private static void initFlowRules() {
    
    
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);

    }

}

4.配置服务消费者,从而服务消费者可以通过 Nacos 的服务注册发现功能从 Nacos server 上获取到它要调用的服务。也是在bootstrap.properties 或者 bootstrap.yml配置
注意是另外一个服务

spring:
  application:
    name: hamal-manage
  cloud:
    nacos:
      config:
        server-addr: http://127.0.0.1:8848
        file-extension: properties
        group: DEFAULT_GROUP

5.通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能。给 RestTemplate 实例添加 @LoadBalanced 注解,开启 @LoadBalanced 与 Ribbon 的集成:

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {
    
    

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
    
    
        return new RestTemplate();
    }

    public static void main(String[] args) {
    
    
        SpringApplication.run(NacosConsumerApplication.class, args);
    }

    @RestController
    public class TestController {
    
    

        private final RestTemplate restTemplate;

        @Autowired
        public TestController(RestTemplate restTemplate) {
    
    this.restTemplate = restTemplate;}

        @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
        public String echo(@PathVariable String str) {
    
    
            return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
        }
    }
}

6.启动NacosConsumerApplication 和DemoApplication 这两个服务访问
http://localhost:8080/echo/2018,返回内容为 Hello Nacos Discovery 2018,并且在DemoApplication 的控制台打印出来请求进来了

猜你喜欢

转载自blog.csdn.net/qq_39684784/article/details/110733537