Rest,服务消费者


Rest服务消费者

编写服务消费者模块

  1. 创建消费者,一般指定端口号为80
  2. pom.xml和application.yml
<?xml version="1.0" encoding="UTF-8"?>

    
        springcloud
        cn.lzm
        1.0-SNAPSHOT
    
    4.0.0

    springcloud-consumer-person-80
    
        
        
            cn.lzm
            API
            1.0-SNAPSHOT
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

    


server:
  port: 80
  1. 将RestTemplate注册到spring IOC容器中
package cn.lzm.springcloud.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class WebConfig {
    
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

  1. 编写控制器,消费者不应该有服务层
package cn.lzm.springcloud.controller;
import cn.lzm.springcloud.pojo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 理解:消费者,不应该有service层
 * RestTemplate... 直接调用注册到spring中
 * (String url, Class responseType, Map uriVariables)路径 响应类字节码 map请求参数
 */
@Controller
public class PersonController {

    @Autowired
    RestTemplate restTemplate;
    private static final String REQUEST_URL = "http://localhost:8001";

    @GetMapping("/person/com/add")
    @ResponseBody
    public String addPerson(Person person){
        //postForObject ,getForObjec ...
        return restTemplate.postForObject(REQUEST_URL+"/person/add",person,String.class);
    }

    @GetMapping("/person/com/get/{id}")
    @ResponseBody
    public Person getPersonById(@PathVariable("id") int id){
        return restTemplate.getForObject(REQUEST_URL+"/person/{id}",Person.class,id);
    }
    @GetMapping("/person/com/get/all")
    @ResponseBody
    public List getPersonAll(){
        return restTemplate.getForObject(REQUEST_URL+"/person/getall",List.class);
    }

}

  1. 测试一下
  • 成功()