本篇要编写的是一个 Eureka 服务消费者,通过 RestTemplate 对象,进行对服务提供者提供的 REST Api 进行访问使用
1. 创建 spring-consumer 项目 (接着先前的项目进行开发)
选中 spring-cloud,右键 new -> Module 创建项目 ?
点击 next ?
填写 ? 的信息,然后点击 next ?
依次按照 ? 的可选项,进行选择,选择完后,点击 next,再点击 Finish 键,则创建好了项目 ?
2. 进行项目配置
首先将 application.properties 通过 alt + shift + r 快捷键修改为 application.yml
在 application.yml 中填写 ? 的配置信息
server:
port: 8020
spring:
application:
name: consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
修改启动类,在 mr.s.consumer 包下打开 SpringConsumerApplication 类
package mr.s.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SpringConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringConsumerApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3. 代码编写
- 创建 Student 实体类对象
在 mr.s.consumer 下创建 entity 包,然后在该包下创建 Student 类 ?
package mr.s.consumer.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private long id;
private String name;
private int age;
}
- 创建 ConsumerHandler
在 mr.s.consumer 包下,创建 controller 包,在该包下创建 ConsumerHandler 类 ?
package mr.s.consumer.controller;
import mr.s.consumer.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 ConsumerHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll() {
return restTemplate.getForObject("http://localhost:8010/student/findAll", Collection.class);
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id) {
return restTemplate.getForObject("http://localhost:8010/student/findById/{id}", Student.class, id);
}
@PostMapping("/save")
public void save(@RequestBody Student student) {
restTemplate.postForLocation("http://localhost:8010/student/save", student);
}
@PutMapping("/update")
public void update(@RequestBody Student student) {
restTemplate.put("http://localhost:8010/student/update", student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id) {
restTemplate.delete("http://localhost:8010/student/deleteById/{id}", id);
}
}