nacos实现Java和.NetCore的服务注册和调用
用nacos作为服务注册中心,如何注册.NetCore服务,如何在Java中调用.NetCore服务呢?可以分为下面几个步骤:
0.运行nacos
1.开发.net core服务,然后调用nacos提供的.net core sdk注册服务。
2.开发Java服务,然后注册服务。
3.用RestTemplate调用.net core服务。
下面来看代码:
0.参考我之前的文章分布式配置nacos搭建踩坑指南(下),首先运行nacos.
1.首先开发一个.net core web api,我们返回的数据是天气预报消息,新建一个WeatherForecastController,代码如下:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
//public String Get()
//{
// return "sunny";
//}
}
}
然后设置好访问的url,在launchSettings.json的修改 "applicationUrl": "http://192.168.1.110:5000",注意这里去掉了https://192.168.1.110:5001,是为了避免在后面Java调用时需要证书的麻烦。
最后我们在cmd中输入dotnet run,当服务正常运行起来后,在浏览器中输入:http://192.168.1.110:5000/weatherforecast,发现成功返回天气数据,格式为json,截图如下:

2.net core项目中引入nuget包:nacos-sdk-csharp,截图如下:

3.调用nacos-sdk-csharp,进行服务注册,代码如下:
using System;
using Microsoft.Extensions.DependencyInjection;
using Nacos.V2;
using Nacos.V2.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NacosDiscoveryProviderNetCoreTest1
{
class Program
{
static async Task Main(string[] args)
{
string serverAddr = "http://localhost:8848";
string dataId = "config2";
string group = "DEFAULT_GROUP";
IServiceCollection services = new ServiceCollection();
//register service
services.AddNacosV2Naming(
x =>
{
x.ServerAddresses = new List<string>() { serverAddr };
//x.ConfigUseRpc = true;
}
);
IServiceProvider serviceProvider = services.BuildServiceProvider();
var namingSvc = serviceProvider.GetService<INacosNamingService>();
await namingSvc.RegisterInstance("weatherforecast", "192.168.1.110", 5000);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(await namingSvc.GetAllInstances("weatherforecast")));
Console.ReadKey();
}
}
}
我们进入nacos后台,如果服务注册成功,我们就会在服务列表中看到weatherforecast服务了,如下所示:

有两个地方必须切记注意:
1).namingSvc.RegisterInstance("weatherforecast", "192.168.1.110", 5000);是一句很关键的代码,意思是注册一个名为weatherforecast,地址为:192.168.1.110,端口为:5000的服务。
2)launchSettings.json里的applicationUrl必须去掉包含https的设置,只保留http的设置,即只保留:"applicationUrl": "http://192.168.1.110:5000",否则在Java中调用会报证书错误。
4.参考nacos服务注册,利用阿里巴巴Spring boot脚手架,引入:spring-boot-starter-web,spring-cloud-starter-alibaba-nacos-discovery,spring-cloud-starter,spring-boot-starter-test,spring-cloud-starter-loadbalancer,spring-cloud-starter-openfeign。完整的pom如下:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nocos-discovery-consumer-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>nocos-discovery-consumer-sample</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version>
<spring-cloud.version>2021.0.4</spring-cloud.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.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.netbeans.external</groupId>
<artifactId>org-apache-commons-httpclient</artifactId>
<version>RELEASE126</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
5.application.properties的设置同前面的文章里介绍的设置一样,代码如下所示:
spring.application.name=nocos-discovery-consumer-sample
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
spring.cloud.nacos.discovery.server-addr=localhost:8848
spring.cloud.nacos.discovery.namespace=public
spring.main.allow-circular-references=true
server.port=9091
6.新建一个名为WeatherService的接口,代码如下:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
@FeignClient("weatherforecast")
@LoadBalancerClient("weatherforecast")
public interface WeatherService {
@GetMapping("/Weatherforecast")
public String getWeather(); }
7.新建一个RestTemplateController,代码如下:
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;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.apache.commons.httpclient.methods.GetMethod;
//import org.apache.http.client.HttpClient;
import org.apache.commons.httpclient.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import java.io.*;
@RestController
public class RestTemplateController {
//@LoadBalanced
@Autowired
public RestTemplate resttemplate; //@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
} @Autowired
private EchoService echoService; @Autowired
private WeatherService weatherService; @Autowired DiscoveryClient discoveryClient; //resttemplate test
@GetMapping("/call/echo")
public String callEcho() { System.out.println("callEcho"); ServiceInstance serviceInstance=discoveryClient.getInstances("weatherforecast").get(0);
System.out.println("Host is: "+serviceInstance.getHost()+" ,port is: "+serviceInstance.getPort());
String urlString=serviceInstance.getHost()+":"+serviceInstance.getPort()+"/weatherforecast";
urlString="http://"+urlString;
//RestTemplate test
return resttemplate.getForObject(urlString, String.class); } //openFeign test
@GetMapping("/getWeather")
public String getWeather() { return weatherService.getWeather();
}
}
其中要注意的几点:
1) ServiceInstanceserviceInstance=discoveryClient.getInstances("weatherforecast").get(0);是一句关键的代码,用于获取weatherforecast服务的实例。
2)callEcho()是调用RestTemplage访问netcore服务
3)getWeather是调用openFeiign访问netcore服务
8.启动类代码如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NocosDiscoveryConsumerSampleApplication {
public static void main(String[] args) {
SpringApplication.run(NocosDiscoveryConsumerSampleApplication.class, args);
}
}
9.运行,访问http://192.168.1.110:5000/weatherforecast和http://localhost:9091/getWeather:


nacos实现Java和.NetCore的服务注册和调用的更多相关文章
- .net core + eureka + spring boot 服务注册与调用
.net core + eureka + spring boot 服务注册与简单的调用 假期小长假遇上疫情只能去家里蹲了,刚好有时间总结一下. 概述 微服务架构是当前比较火的分布式架构,本篇基于.ne ...
- 基于SpringCloud的服务注册和调用
一:服务的注册和发现 Eureka是Netflix开源的一款提供服务注册和发现的产品,它提供了完整的Service Registry(注册登记)和Service Discovery(发现)实现.也是s ...
- Spring Cloud Alibaba 实战 之 Nacos 服务注册和发现
服务注册与发现,服务发现主要用于实现各个微服务实例的自动化注册与发现,是微服务治理的核心,学习 Spring Cloud Alibaba,首先要了解框架中的服务注册和发现组件——Nacos. 一.Sp ...
- SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇
Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全 ...
- Zookeeper服务注册与发现原理浅析
了解Zookeeper的我们都知道,Zookeeper是一种分布式协调服务,在分布式应用中,主要用来实现分布式服务的注册与发现以及分布式锁,本文我们简单介绍一下Zookeeper是如何实现服务的注册与 ...
- 搞懂Dubbo服务发布与服务注册
一.前言 本文讲服务发布与服务注册,服务提供者本地发布服务,然后向注册中心注册服务,将服务实现类以服务接口的形式提供出去,以便服务消费者从注册中心查阅并调用服务. 本文源码分析基于org.apache ...
- Dubbo之服务注册
在上一篇文章Dubbo之服务暴露分析中介绍了当远程暴露时,如果有注册中心,需要在服务暴露后再将服务注册到注册中心.该篇将介绍该功能的有关步骤. 注册的起点 在RegistryProtocol.expo ...
- springcloud(三):服务提供与调用
上一篇文章我们介绍了eureka服务注册中心的搭建,这篇文章介绍一下如何使用eureka服务注册中心,搭建一个简单的服务端注册服务,客户端去调用服务使用的案例. 案例中有三个角色:服务注册中心.服务提 ...
- 三、spring cloud 服务提供与调用
如何使用eureka服务注册中心,搭建一个简单的服务端注册服务,客户端去调用服务使用. 案例中有三个角色:服务注册中心.服务提供者.服务消费者,eureka单机版启动既可,流程是首先启动注册中心,服务 ...
- spring cloud(三)服务提供与调用
服务提供 我们假设服务提供者有一个hello方法,可以根据传入的参数,提供输出“hello xxx,this is first messge”的服务 1.pom包配置 创建一个springboot项目 ...
随机推荐
- 2022-4-6内部群每日三题-清辉PMP
1.产品负责人一直听取一个项目干系人的意见,远远超过其他项目干系人.敏捷管理专业人士应该怎么做? A.允许这名干系人和产品负责人自己解决问题. B.与这名干系人安排一次私人会议,以澄清他们的需求. C ...
- Mac怎么创建加密文件夹
对于一些使用Mac工作生活有特殊要求以及职业要求有限制的用户来说,加密自己的工作内容以及隐私是非常重要的一件事情.往往用户需要加密的内容项目很多,这个时候我们就需要一个加密文件夹来包含这些内容.那么M ...
- 如何修改Mac文件默认打开方式?
熟悉Mac电脑的用户都知道,在 OS X 中,Finder 存储的文件总会以指定的某个默认应用程序打开,比如图片类型的文件默认以「预览」打开.但由于经常需要使用图片编辑工具 PS打开图片类型的文件,每 ...
- Software--BigData--StreamingData
2018-03-29 16:13:34 一 : 流系统分层架构设计 二: 分层技术选型分析 三:底层 -- 服务配置和协调 ZooKeeper
- JS篇(002)-JavaScript 中如何检测一个变量是一个 String 类型?
答案:三种方法(typeof.constructor.Object.prototype.toString.call()) 解析: ①typeof typeof('123') === "str ...
- 【Java】zuul
报错 com.netflix.zuul.exception.ZuulException: Hystrix Readed time out 解决办法,zuul模块的yml配置文件增加 ribbon: C ...
- IDEA+SpringBoot整合Swagger2创建API文档
------------恢复内容开始------------ 1.创建SpringBoot项目 2.选择快捷方式创建springboot项目 3.工程文件树形图 4.pom.xml中导入Swagger ...
- 逆向学习物联网-网关ESP8266-01硬件原理及平台搭建
1.系统原理 2.ESP8266网关的内部原理框图 1)STM32通过COM2以AT指令与ESP-01进行通讯,实现MQTT协议, 2)将COM3收到的JSON数据,透明传输到云端 3)通过COM2收 ...
- Mysql学习:2、mysql基本命令
1.下载安装好的mysql分为两种数据库: a.系统自带: b.用户自己创建: 2.基本命令: create database 数据库名称; // 创建数据库:记住后面加 分号 drop databa ...
- noi 1.5 1 求平均年龄
描述 班上有学生若干名,给出每名学生的年龄(整数),求班上所有学生的平均年龄,保留到小数点后两位. 输入 第一行有一个整数n(1<= n <= 100),表示学生的人数.其后n行每行有1个 ...