一、nacos与Eureka有相同的三个对象:注册中心、服务提供者、服务消费者

首先在官方下载nacos程序包,点击\nacos\bin\startup.cmd启动
在这里插入图片描述

二、编写provider

1.修改pom,添加maven依赖



<properties>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<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-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-alibaba-dependencies</artifactId>
			<version>2.1.0.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

2、修改yml配置文件

server:
  port: 8888

spring:
  main:
    allow-bean-definition-overriding: true
  application:
    name: TIS
  server:
    ip: 192.168.70.107
  cloud:
    nacos:
      config:
        file-extension: yml
        server-addr: ${spring.server.ip}:18001
        extension-configs:
          - data-id: are-test.yaml
            group: test
            refresh: true
      discovery:
        server-addr: ${spring.server.ip}:18001
  profiles:
    include: common
    active: local

spring.cloud.nacos.discovery.server-addr指定注册中心的地址,如果你不需要注册该服务,也可以去掉该项,并删除discovery依赖
spring.cloud.nacos.config.server-addr指定配置中心的地址
file-extension指定配置中心中配置文件的格式
3、启动类添加@EnableDiscoveryClient

三、编写consumer

依赖多一个

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>

1.与provider基本一致,使用resttemplate调用服务测试

    @Autowired
    LoadBalancerClient loadBalancerClient;
    @GetMapping("blindPlateManage")
    public Map<String, Object> findBlindPlates(@RequestParam Map<String, String> tableMap){
        ServiceInstance instance = loadBalancerClient.choose("mare-code-generator");
        String url = instance.getUri() + "/code/generateCode";
        RestTemplate restTemplate = new RestTemplate();
        Map postData = new HashMap(16);
        Map datas = new HashMap(16);
        datas.put("tankAreaCode","001");
        postData.put("code","TK");
        postData.put("datas",datas);
        String result = restTemplate.postForObject(url, postData,String.class);
        String jsonObject = JSONObject.parseObject(JSONObject.parseObject(result).get("result").toString()).get("data").toString();
        return blindPlateManageService.findBlindPlates(tableMap);
    }

2.或者在NacosConsumerApplication启动文件上加上@EnableFeignClients注解开启FeignClient的功能。
在nacos-consumer的pom文件引入以下的依赖:

<dependency>
	<groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

@RestController
public class ConsumerController {


    @Autowired
    ProviderClient providerClient;

    @GetMapping("/hi-feign")
    public String hiFeign(){
       return providerClient.hi("feign");
    }
}

3.或者

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@RequestMapping("discovery")
public class DiscoveryController {

    @NacosInjected
    private NamingService namingService;

    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}

4.或者

 @Autowired
 private DiscoveryClient discoveryClient;

@GetMapping("getInstances")
    public List<ServiceInstance> getInstances(){
        //查询指定服务的所有实例信息
        //无论使用什么做注册中心都可以使用consul、eureka、zookeeper
        return discoveryClient.getInstances("user-center");
    }

    @GetMapping("getServices")
    public List<String> getServices(){
        //查询该注册中心有多少个服务
        return discoveryClient.getServices();
    }

5.或者
在main主入口类添加@EnableFeignClients启用注解

@EnableFeignClients
......

新增interface


import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
 
import cn.test.bean.User;
 
 
@FeignClient(value = "config-service")
@Component
public interface FindService {
 
    @GetMapping(value="s")
    String helloServer(@RequestParam("username")String username);
 
    @PostMapping(value="u")
    String helloUser(@RequestBody User user);
 

注入服务并使用


    @Autowired 
    private FindService service;
 
    @GetMapping("/find")
    String find(String param) {
        return "find " + service.helloServer(param);
    }
 
    @PostMapping("/f")
    String findU(@RequestBody User user) {
        return "find " + service.helloUser(user);
    }
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐