SpringCloud服务注册
pom.xml
<!--SpringCloud 服务注册和发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>
bootstrap.properties
server.port=9091
spring.application.name=provider
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
单独使用配置中心的地址也可以,分开写可以区分注册中心和配置中心
spring.cloud.nacos.server-addr=127.0.0.1:8848
启动类使用
@EnableDiscoveryClient
开启服务注册
MyApplication
package com.lmcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
}
服务提供者的方法
package com.lmcode.ccontroller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/provider")
public String provider(){
return "provider";
}
}
SpringCloud服务发现
pom.xml
<!--SpringCloud 服务注册和发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>
application.properties
server.port=9092
spring.application.name=consumer
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
通过定义一个RestTemplate发送http请求并调用服务
Application
package com.lmcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
ConsumerController
package com.lmcode.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
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")
public String echo(){
// provider服务的provider方法
return restTemplate.getForObject("http://provider/provider",String.class);
}
}
标签:服务,SpringCloud,provider,nacos,springframework,import,org,public,cloud From: https://www.cnblogs.com/lm02/p/18149811