SpringCloud-EurekaClient
创建Module pom.xml
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
spring:application:name: provider # 应用程序的名称,通常用于服务注册server:port: 8010 # 服务器监听的端口号eureka:client:service-url:defaultZone: http://localhost:8761/eureka/ # Eureka 服务器的地址,用于注册服务instance:prefer-ip-address: true # 是否将当前 IP 地址进行注册到EurekaService
创建代码
package com.cloud.eurekaclient.controller;import com.cloud.eurekaclient.entity.Student;
import com.cloud.eurekaclient.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.Collection;@RestController
@RequestMapping("/student")
public class StudentHandler {@Autowiredprivate StudentRepository studentRepository;@GetMapping("/findAll")public Collection<Student> findAll(){return studentRepository.findAll();}@GetMapping("/findById/{id}")public Student findById(@PathVariable("id") long id){return studentRepository.findById(id);}@PostMapping("/save")public void save(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@PutMapping("/update")public void update(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@DeleteMapping("/deleteByI/{id}")public void deleteById(@PathVariable("id") long id){studentRepository.deleteById(id);}
}
package com.cloud.eurekaclient.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;
}
package com.cloud.eurekaclient.repository.impl;import com.cloud.eurekaclient.entity.Student;
import com.cloud.eurekaclient.repository.StudentRepository;
import org.springframework.stereotype.Repository;import java.util.Collection;
import java.util.HashMap;
import java.util.Map;@Repository
public class StudentRepositoryImpl implements StudentRepository {private static Map<Long,Student> studentMap;static{studentMap = new HashMap<>();studentMap.put(1L,new Student(1L,"张三",22));studentMap.put(2L,new Student(2L,"李四",32));studentMap.put(3L,new Student(3L,"王五",41));studentMap.put(4L,new Student(4L,"徐6",53));}@Overridepublic Collection<Student> findAll() {return studentMap.values();}@Overridepublic Student findById(long id) {return studentMap.get(id);}@Overridepublic void saveOrUpdate(Student student) {studentMap.put(student.getId(),student);}@Overridepublic void deleteById(long id) {studentMap.remove(id);}
}
apipost自行测试可以