1.首先创建一个名叫sca-provider的工程,在pom.xml文件里添加依赖如下
org.springframework.boot
spring-boot-starter-web
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
2.在sca-provider项目中创建服务提供方对象,基于此对象对外提供服务(基于此对象处理客户端的请求)
------在此项项目中创建如下包名,并且创建ProviderController类,提供一个处理请求的方法(谁来访问我这个服务,谁就是客户端也就是服务消费方)
package com.jt.provider.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
@Value("${server.port:8080}")
private String server;
@GetMapping("/provider/echo/{msg}")
//这里的msg jdk8可以不用写,如果想兼容jdk5 必须写
public String doRestEcho1(@PathVariable("msg") String msg){
return server +"say hello"+msg;
}
}
3.--------------访问的第一种方式 基于一下网址访问
http://localhost:8081/provider/echo/tedu
//tedu可以改
---------------第二种方式,在sca-consumer工程中对这个服务进行访问
创建服务消费者工程(module名为sca-consumer),继承parent工程(01-sca),其pom.xml文件内容如下
01-sca com.jt 1.0-SNAPSHOT 4.0.0 sca-consumerorg.springframework.boot spring-boot-starter-webcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
创建sca-consumer服务中的配置文件application.yml,关键代码如下
server:
port: 8090
spring:
application:
name: sca-consumer #服务注册时,服务名必须配置
cloud:
nacos:
discovery:
server-addr: localhost:8848 #从哪里去查找服务
创建消费端启动类并实现服务消费,关键代码如下:
package com.jt;
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}
在sca-consumer启动类中添加如下方法,用于创建RestTemplate对象(RestTemplate这个类是由Spring提供的,它的作用是:通过他来进行远端的服务调用)
@Bean
public RestTemplate restTemplate(){//基于此对象实现远端服务调用
return new RestTemplate();
}
定义sca-consumer服务的消费端Controller,在此对象方法内部实现远端服务调用
package com.jt.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer/doRestEcho1")
public String doRestEcho01(){
//1.定义要调用的远端服务的url
String url="http://localhost:8081/provider/echo/8090";
//2.基于restTemplate对象中的相关方法进行服务调用
return restTemplate.getForObject(url, String.class);
}
}
启动消费者服务,并在浏览器输入如下地址进行访问测试
http://localhost:8090/consumer/doRestEcho1
在进行以上操作时,必须打开nacos,否则失败



