1.生产者注册
1.1 添加依赖
<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>
1.2 启动类
1.3 配置application.yml文件
1.4设置Controller层接收请求
1.5 页面效果
2.消费者调用
消费端调用提供端
nacos的关系
2.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>01-sca</artifactId>
<groupId>com.jt</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>sca-concumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.jt</groupId>
<artifactId>sca-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.jt</groupId>
<artifactId>sca-provider</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!--添加nacos服务注册和发现依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--添加springboot web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2.2 配置application.yml文件
server:
port: 8090
spring:
application:
name: sca-concumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
2.3 创建启动类
2.4 创建Controller层
package com.jt.concumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/*定义服务消费端 在这层的方法中通过一个对象实现对远端服务sca-provider的调用*/
@RestController
public class ConcumerController {
/*通过此对象调用远端服务*/
@Autowired
private RestTemplate restTemplate;
/*读取配置文件中的属性值然后赋值给appName*/
@Value("${spring.application.name}")
private String appName;
@GetMapping("/concumer/doRestEcho1")
public String doRestEcho1(){
//1.定义要调用的远端服务的url
String url="http://localhost:8081/provider/echo/"+appName;
//2.基于restTemplate的对象中的方法进行服务调用
return restTemplate.getForObject(url, String.class);
}
}