二:RestTemplate

通过RestTemplate可以实现不同微服务之间的调用

RestTemplate是spring框架提供的一种基于RESTful的服务组件,底层对HTTP请求及其相应进行了封装,提供了很多的远程访问REST服务的方式,可以简化代码的开发

如何使用RestTemplate

1.创建maven工程

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springCloud02</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.7.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

2.创建实体类:

package com.southwind.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}

3.持久层

接口:

package com.southwind.repository;

import com.southwind.entity.User;

import java.util.Collection;

public interface UserRepository {
    public Collection<User> findAll();
    public User findById(Integer id);
    public void saveOrUpdate(User user);
    public void deleteById(Integer id);
}

实体类:

package com.southwind.repository.impl;

import com.southwind.entity.User;
import com.southwind.repository.UserRepository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class UserRepositoryImpl implements UserRepository {
    private static Map<Integer,User> map;
    static {
        map=new HashMap<>();
        map.put(1,new User(1,"张三"));
        map.put(2,new User(2,"李四"));
        map.put(3,new User(3,"王五"));

    }
    @Override
    public Collection<User> findAll() {
        return map.values();
    }

    @Override
    public User findById(Integer id) {
        return map.get(id);
    }

    @Override
    public void saveOrUpdate(User user) {
        map.put(user.getId(),user);
    }

    @Override
    public void deleteById(Integer id) {
        map.remove(id);
    }
}

测试接口可以使用

RestTemplate访问服务REST服务

1.将RestTemplate的实例化对象通过@Bean注解注入到IoC容器

package com.southwind.config;

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

@Configuration
public class MyConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  • 方法名为id名

2.创建RestHandler

package com.southwind.Handler;

import com.southwind.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;

@RestController
@RequestMapping("/rest")
public class RestHandler {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/findall")
    public Collection<User> findAll(){
        return restTemplate.getForObject("http://localhost:8080/user/findall",Collection.class);
    }
    @GetMapping("/findbyid/{id}")
    public User findById(@PathVariable("id") Integer id){
        return restTemplate.getForObject("http://localhost:8080/user/findbyid/{id}",User.class,id);
    }
    @PostMapping("/save")
    public void save(@RequestBody User user){
         restTemplate.postForObject("http://localhost:8080/user/save",user,Collection.class);
    }
    @PutMapping("/update")
    public void update(User user){
        restTemplate.put("http://localhost:8080/user/save",user);
    }
    @DeleteMapping("/delete{id}")
    public void delete(@PathVariable("id") Integer id){
        restTemplate.delete("http://localhost:8080/user/delete{id}",id);
    }
}

底层RestTemplate是对http请求和相应的封装,提供了很多访问远程REST服务的方法,基于它的这个特性,我们可以实现不同微服务之间的调用。

服务消费者

1.创建Module,配置环境

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springCloud01</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>consumer</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
</project>

2.application.yml

server:
  port: 8020
spring:
  application:
    name: consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

3.启动类:

package com.southwind;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
}

4.Handler

package com.southwind.controller;

import com.southwind.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;

@RestController
@RequestMapping("/consumer")
public class StudentHandler {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/findall")
    public Collection<Student> findall(){
        return restTemplate.getForObject("http://localhost:8010/provider/findall",Collection.class);
    }
    @GetMapping("/findbyid/{id}")
    public Student findById(@PathVariable("id") Integer id){
        return restTemplate.getForObject("http://localhost:8010/provider/findbyid/{id}",Student.class,id);
    }
    @PostMapping("/save")
    public void save(@RequestBody Student student){
        restTemplate.postForObject("http://localhost:8010/provider/save",student,Collection.class);
    }
    @DeleteMapping("/delete")
    public void deletebyid(Integer id){
        restTemplate.delete("http://localhost:8010/provider/delete/{id}",id);
    }
}

5.配置类:

package com.southwind.config;

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

@Configuration
public class MyConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
posted on 2022-06-23 23:10  Steam残酷  阅读(137)  评论(0)    收藏  举报