二: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();
}
}

最新文章

  1. JAVA学习Swing章节流布局管理器简单学习
  2. winform 在指定目录下已经生成资源Image图片的方式
  3. javascript中window.event事件用法详解
  4. 点击其它地方隐藏div/事件冒泡/sweet-alert阻止冒泡
  5. MVC 部分视图
  6. mysql 执行reset master 风险
  7. AOP 笔记
  8. 【原创】shadowebdict开发日记:基于linux的简明英汉字典(二)
  9. ELF二进制目标文件详解
  10. [ An Ac a Day ^_^ ] [kuangbin带你飞]专题十二 HDU 1176 免费馅饼
  11. 【源码解析】BlockManager详解
  12. Pyhton编程(五)之基本数据类型-列表、元组、字典
  13. Linux查询一台机器的IP地址和其对应的域名
  14. 浅析PHP正则表达式的利用技巧
  15. AX2012 ERP Excel报表方案
  16. gradle 排除jar包依赖
  17. CodeForces round 967 div2 题解(A~E)
  18. leetcode53
  19. Atiit 常见功能 常用功能与模块的最快速解决方案
  20. 编译openssl失败(SLES11.3), undefined reference to `OPENSSL_cpuid_setup&#39;

热门文章

  1. Codeforces Round #834 (Div. 3) A-G
  2. 图扑 Web SCADA 零代码组态水泥生产工艺流程 HMI
  3. &lt;二&gt;派生类的构造过程
  4. qtcreator 报错error: You need to set an executable in the custom run configuration.
  5. qtcreator配置cmake+mingw开发环境
  6. React Server Component: 混合式渲染
  7. Redis的数据被删除,占用内存咋还那么大?
  8. STM32标准库中GPIO_ReadInputData与GPIO_ReadInputDataBit的区别
  9. USB转TTL串口 (CH340 G)
  10. Prometheus高可用架构介绍