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 的控制台打印出来请求进来了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值