说明
本篇文章主要配置consumer如何调用provider的。
微服务中,项目之间的调用使用http协议进行处理的。
msc-consumer
配置RestTemplate
创建配置类,配置管理RestTemplate,在项目中使用RestTemplate去访问msc-provider接口。
package team.one.msc.consumer.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Created by lankk on 2020/5/14.
*
* @author lankk
* @date 2020/5/14
*/
@Configuration
public class RestTmplateConfig {
/**
* 注解 @Bean 表示这是由spring管理的类,返回值 RestTemplate 就是要管理的类,方法名 restTemplate 是类的id
* <p>
* 和下面在xml文件的配置相同
* <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
ConsumController改动
package team.one.msc.consumer.controller;
import lombok.extern.slf4j.Slf4j;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Created by lankk on 2020/5/12.
*
* @author lankk
* @date 2020/5/12
*/
@Slf4j
@RestController
@RequestMapping("/csm")
public class ConsumController {
@Autowired
private RestTemplate restTemplate;
@Value("${provider.url}")
private String providerUrl;
/**
* 简单测试
*
* @param id
* @return
*/
@GetMapping("/get/{id}")
public String getId(@PathVariable int id) {
log.info("ConsumController.getId,入参id={}", id);
// 访问msc-provider
String result = restTemplate.getForObject(providerUrl.concat("/pvd/test/").concat(String.valueOf(id)), String.class);
log.info(result);
return "传参:" + id + ",返回:" + result;
}
}
yml配置
server:
# 本服务的端口号
port: 8080
spring:
application:
# 服务名称,集群中的每个实例的服务名称是相同的
name: msc-consumer
eureka:
client:
# 消费者需要向eureka server注册,以后Gateway要向server拉取消费者实例
register-with-eureka: true
# 从eureka server中拉取注册的eureka client实例信息
fetch-registry: true
service-url:
# 消费者需要向eureka server获取生产者地址,多个之间使用【,】隔开
defaultZone: http://eureka01:7001/eureka/
instance:
instance-id: 消费者01
# 自定义属性
provider:
# msc-provider的地址
url: http://localhost:18080/
启动测试
启动msc-eureka-server、msc-consumer和msc-provider项目。
浏览器中输入 http://localhost:8080/csm/get/561 访问。