创建 Maven 工程
父工程依赖
<!--springcloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
=================================================
//使用 RestTemplate 远程访问http服务,需要先注入到spring
@Autowired
private RestTemplate restTemplate;
private static final String REST_URL_PREFIX = "http://localhost:8081";
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept){
System.out.println(dept);
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
}
//依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
//application.yml配置
server:
port: 7003
#Eureka配置
eureka:
instance:
hostname: eureka7003 #服务端名称
client:
register-with-eureka: false #是否向 eureka 注册
fetch-registry: false #是否向 eureka 获取信息
service-url:
defaultZone: http://localhost:7001/eureka/
//依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
//提供方 application.yml配置
spring:
application:
name: springcloud-provide
#Eureka配置,服务注册
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
//消费方 application.yml配置
#eureka配置
eureka:
client:
register-with-eureka: false #不向eureka注册
service-url:
defaultZone: http://localhost:7001/eureka/
//消费方使用**服务名**调用服务
//eureka 通过服务名访问
private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDE";
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept){
System.out.println(dept);
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
}
原文:https://www.cnblogs.com/lq-404/p/15176223.html