728x90
반응형
Docker에 설치한 Cassandra(Single Node)와 SpringBoot 연동
*spring-boot-starter-parent 2.3.10.RELEASE 기준
*자세한 설명 생략
▷ Project 전체 구조
*파일 이름으로 검색 가능
▷ Coulmn Family Create
*Cassandra 설치 방법 아래 관련 글 참고
*example을 위한 Table
/** KEYSPACE 생성 */
-- CREATE KEYSPACE testDB WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor': 2};
-- → class :
-- → SimpleStrategy : 단일 데이터 센터
-- → NetworkTopologyStrategy : 멀티 데이터 센터
--→ replication_factor : 복제본 수 설정
/** KEYSPACE 접속 */
-- USE testDB;
/** 테이블 생성 */
CREATE TABLE users ( user_id int PRIMARY KEY, fname text, lname text );
/** 데이터 생성 */
INSERT INTO users (user_id, fname, lname) VALUES (1745, 'john', 'smith');
/** 데이터 조회 */
SELECT * FROM users;
▷ Maven Dependency(application.properties)
*Spring Boot는 Cassandra에 대한 자동 구성과 Spring Data Cassandra에서 제공하는 추상화를 제공
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
▷ CassandraConfig.java
*Default DataCenterName : datacenter1
*Default UserNmae/Passworrd : cassandra/cassandra
*Keyspace : 위에서 생성한 name
package com.example.test;
import java.net.InetSocketAddress;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.datastax.oss.driver.api.core.CqlSession;
/**
* Cassandra Test Sample
*
* Cassandra Configuration and CqlSession Create
*/
@Configuration
public class CassandraConfig {
@Bean
public CqlSession session() {
return CqlSession.builder()
.addContactPoint(new InetSocketAddress("127.0.0.1", 9042))
// @JHLee. → Cassandra 인증/권한 설정 후 적용(기본 설정으로 사용 중)
// .withAuthCredentials("cassandra", "cassandra")
.withLocalDatacenter("datacenter1")
.withKeyspace("testdb")
.build();
}
}
▷ TestRepository.java
package com.example.test.testdb.repository;
import org.springframework.data.cassandra.repository.CassandraRepository;
import com.example.test.testdb.dto.TestDTO;
/**
* Cassandra Test Sample
*
* TestRepository
*/
public interface TestRepository extends CassandraRepository<TestDTO, Integer> {
/*
▶ Crudrepository vs Jparepository
* 단순 CRUD 작업만 하기 때문에 Crudrepository 사용
* CassandraRepository는 Crudrepository를 상속
* 그 외 Paging, Sorting, JPA 특화 기능들이 필요하면 JpaRepository 고려
- Crudrepository : CRUD 관련 기능들을 제공
- JpaRepository : Crudrepository + JpaRepository
*/
}
▷ TestDTO.java
package com.example.test.testdb.dto;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import lombok.Data;
/**
* Cassandra Test Sample
*
* users Table
*/
@Data
@Table("users")
public class TestDTO {
@PrimaryKey
private int user_id;
private String fname;
private String lname;
}
▷ 결과 확인
*애플리케이션을 실행하면 간단히 확인 가능
*아래 내용은 Post Man을 통해 테스트하기 위한 코드
① Test용 API생성(사용자 조회)
- TestController.java
package com.example.test.test.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.test.test.service.TestService;
import com.example.test.test.service.vo.TestReqVO;
import com.example.test.test.service.vo.TestResVO;
/**
* Cassandra Test Sample
*
* 사용자 조회
*
*/
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@PostMapping("/getUser.do")
public TestResVO getUser(@RequestBody TestReqVO reqVO) {
TestResVO resVO = new TestResVO();
try {
/** 사용자 조회 */
resVO = testService.findById(Integer.parseInt(reqVO.getUser_id()));
} catch (Exception e) {
// TODO: handle exception
}
return resVO;
}
}
- TestReqVO.java
package com.example.test.test.service.vo;
import lombok.Data;
/**
* Cassandra Test Sample
*
* 사용자 조회 요청 VO
*/
@Data
public class TestReqVO {
/** 사용자 ID */
String user_id;
}
- TestResVO.java
package com.example.test.test.service.vo;
import com.example.test.testdb.dto.TestDTO;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;
/**
* Cassandra Test Sample
*
* 사용자 조회 응답 VO
*/
@Data
@JsonInclude(value = Include.NON_NULL)
public class TestResVO {
/** Result Code */
String resultCode = "0000";
/** Result Msg */
String resultMsg = "성공";
/** 사용자 정보 */
TestDTO userInfo;
}
- TestService.java
package com.example.test.test.service;
import com.example.test.test.service.vo.TestResVO;
/**
* Cassandra Test Sample
*
* TestService
*/
public interface TestService {
/** 사용자 조회 */
public TestResVO findById(Integer user_id);
}
- TestServiceImpl.java
package com.example.test.test.service.impl;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.test.test.service.TestService;
import com.example.test.test.service.vo.TestResVO;
import com.example.test.testdb.dto.TestDTO;
import com.example.test.testdb.repository.TestRepository;
/**
* Cassandra Test Sample
*
* TestServiceImpl
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestRepository testRepository;
/**
* 사용자 조회
*/
@Override
public TestResVO findById(Integer user_id) {
TestResVO resVO = new TestResVO();
try {
// @JHLee. → 공통 처리 필요
if ("".equals(user_id)) {
resVO.setResultCode("9999");
resVO.setResultMsg("필수 요청 값이 누락됬습니다.");
return resVO;
}
/** 사용자 조회 */
Optional<TestDTO> dto = testRepository.findById(user_id);
// @JHLee. → 공통 처리 필요
if(dto.isEmpty()){
resVO.setResultCode("9998");
resVO.setResultMsg("조회 결과가 없습니다.");
return resVO;
}
/** 응답 */
resVO.setUserInfo(dto.get());
} catch (Exception e) {
// TODO: handle exception
}
return resVO;
}
}
② API 요청 결과
▷ 관련 글
728x90
728x90
'▶ Back-End > Java' 카테고리의 다른 글
Random LocalDate 생성 (0) | 2023.09.21 |
---|---|
SpringBoot + Cassandra 연동(Multi Node) (0) | 2023.08.18 |
Cassandra 설치 방법과 간단한 Node 분산 Test (0) | 2023.08.08 |
SLF4J 기본 사용 방법 (0) | 2023.08.07 |
Custom Annotation 생성 Example (0) | 2023.07.26 |
댓글