您是否可以使用地图来存储数据而不是内存数据库?

时间:2019-04-28 21:26:17

标签: spring-boot

我正在编写一个简单的应用程序来接收http请求并将其填充到Map中,我将需要对其进行访问和修改,以适应在Spring Boot中运行的应用程序的跨度。代替使用H2数据库之类的东西,是否可以使用静态地图来完成此任务?

1 个答案:

答案 0 :(得分:0)

是的,有可能。

@SpringBootApplication
public class ExampleApplication {

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

    @RestController
    @RequestMapping("/api/student")
    static class StudentResource {

        private final StudentInMemoryRepository repository;

        StudentResource(StudentInMemoryRepository repository) {
            this.repository = repository;
        }

        @GetMapping
        public ResponseEntity<Collection<Student>> findAll() {
            Collection<Student> students = repository.findAll();
            if (students.isEmpty())
                return ResponseEntity.noContent().build();

            return ResponseEntity.ok(students);
        }

        @PostMapping
        public ResponseEntity<Student> saveOrUpdate(@RequestBody Student student) {
            return ResponseEntity.ok(repository.saveOrUpdate(student));
        }
    }


    @Repository
    static class StudentInMemoryRepository {

        private Map<String, Student> students = new ConcurrentHashMap<>();

        Student saveOrUpdate(Student student) {
            if (student.getId() == null) {
                student.setId(UUID.randomUUID().toString());
            }
            students.put(student.getId(), student);

            return student;
        }

        Collection<Student> findAll() {
            return students.values();
        }
    }

    static class Student {
        private String id;
        private String name;
        private int age;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

一些样品要求

curl --request POST \
  --url http://localhost:8080/api/student \
  --header 'Content-Type: application/json' \
  --data '{\n   "name": "Marc Twain",\n "age" : 17\n}'


curl --request POST \
  --url http://localhost:8080/api/student \
  --header 'Content-Type: application/json' \
  --data '{\n   "name": "John Doe",\n   "age" : 16\n}'


curl --request GET \
  --url http://localhost:8080/api/student \

输出:

[

   {
        "id": "6c1a54d6-ab9b-4f24-b0d4-a62f0eb625c5",
        "name": "John Doe",
        "age": 16
    },
    {
        "id": "a4c18447-d598-4705-8528-6949cc900183",
        "name": "Marc Twain",
        "age": 17
    }
]