GraphQL이란 무엇이고 어떤 장단점이 있을까요?
답 보기
- GraphQL은 Facebook이 개발한 API용 쿼리 언어
- 장점
- 필요한 리소스만 요청할 수 있어 네트워크 비용 감소
- 하나의 엔드포인트로 관리할 수 있어서 관리 포인트 감소
- 단점
- 보안에 안좋음
- 캐싱이 기본적으로 불가능함
- 러닝 커브
- 예시
- 아래와 같이 하나의 graphql이라는 하나의 endpoint에 직접 쿼리를 전송함
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"query": "query { getAllBooks(orderBy: \"title\", page: 0, size: 5) { id title author } }"
}' \
http://localhost:8080/graphql
- 구현 방법
- 구현할 endpoint는 따로 없고 type을 따로 정의한 후 component로 사용 가능한 method를 정의해줌
- service에는 GraphQL과 Repository를 이어주는 로직
- type 정의
-
type Query { getAllBooks: [Book] getBookById(id: ID!): Book } type Mutation { createBook(title: String!, author: String!): Book updateBook(id: ID!, title: String, author: String): Book deleteBook(id: ID!): Boolean } type Book { id: ID! title: String! author: String! }
-
- Java 코드
-
@Component public class BookResolver { private final BookRepository bookRepository; public BookResolver(BookRepository bookRepository) { this.bookRepository = bookRepository; } // Query Resolvers public List<Book> getAllBooks() { return bookRepository.findAll(); } public Optional<Book> getBookById(Long id) { return bookRepository.findById(id); } // Mutation Resolvers public Book createBook(String title, String author) { Book book = new Book(); book.setTitle(title); book.setAuthor(author); return bookRepository.save(book); } public Book updateBook(Long id, String title, String author) { Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("Book not found")); if (title != null) book.setTitle(title); if (author != null) book.setAuthor(author); return bookRepository.save(book); } public boolean deleteBook(Long id) { if (bookRepository.existsById(id)) { bookRepository.deleteById(id); return true; } return false; } } @Component public class BookGraphQLController implements GraphQLQueryResolver, GraphQLMutationResolver { private final BookResolver bookResolver; public BookGraphQLController(BookResolver bookResolver) { this.bookResolver = bookResolver; } // Query public List<Book> getAllBooks() { return bookResolver.getAllBooks(); } public Book getBookById(Long id) { return bookResolver.getBookById(id).orElse(null); } // Mutation public Book createBook(String title, String author) { return bookResolver.createBook(title, author); } public Book updateBook(Long id, String title, String author) { return bookResolver.updateBook(id, title, author); } public boolean deleteBook(Long id) { return bookResolver.deleteBook(id); } }
-
왜 Redis 쓰셨나요?
답 보기
- Memcached와의 비교
- Memcached 단점
- pub/sub, sorted set, hyperloglog 등을 지원하지 않음
- 캐시 교체정책을 lru밖에 지원하지 않음
- replication, sharding을 지원하지 않음
- 트랜잭션이 안됨
- Redis는 트랜잭션, Lua Script 등으로 Atomic 연산을 수행하는 다양한 방법이 있음
- Memcached 장점
- 다중 스레드를 사용해서 동작하기 때문에 대규모 데이터 세트를 저장하고 관리할 때 더 빠른 성능을 보임
- Reference
- Memcached 단점