[TIL] 241129

MONA·2024년 11월 29일

나혼공

목록 보기
38/92

ㅋㄷㅋㅌ

프로그래머스-로또의 최고 순위와 최저 순위

HashSet
java.util 패키지에 포함된 집합 자료 구조.
중복 비허용, 순서 유지 x, 빠른 검색, 추가, 삭제 작업 제공
해시 테이블 기반으로 동작

특징
1. 중복 불허
2. 순서 보장하지 않음
3. 빠른 검색, 삽입, 삭제: O(1) 시간 복잡도로 요소를 검색, 추가, 삭제할 수 있음
4. null 허용
5. 스레드 안전하지 않음: 멀티스레드 환경에서는 Collections.synchronizedSet() 또는 ConcurrentHashMap 사용

주요 메서드

메서드설명
add(E e)요소를 추가. 중복된 값은 추가되지 않음
contains(Object o)특정 요소가 포함되어 있는지 확인
remove(Object o)특정 요소를 제거
size()현재 집합에 포함된 요소의 개수를 반환
isEmpty()집합이 비어 있는지 확인
clear()모든 요소를 제거하여 집합을 비움
iterator()요소를 순회할 수 있는 Iterator를 반환
addAll(Collection<\? extends E> c)다른 컬렉션의 모든 요소를 추가
retainAll(Collection<\?> c)특정 컬렉션과의 교집합만 유지
removeAll(Collection<\?> c)특정 컬렉션에 포함된 요소를 모두 제거

프로그래머스-옹알이(2)

정규식 사용

class Solution {
    public int solution(String[] babbling) {
        int cnt = 0;
        String[] validWords = {"aya", "ye", "woo", "ma"};
        for(String talk: babbling) {
            if(talk.matches("^(aya|ye|woo|ma)+$")) {
                boolean isValid = true;
                for(int i = 0; i < validWords.length; i++) {
                    if(talk.contains(validWords[i] + validWords[i])) {
                        isValid = false;
                        break;
                    }
                }
                if(isValid){
                    cnt++;
                }
            }
        }
        return cnt;
    }
}
  • "^(aya|ye|woo|ma)+$"
    • ^ : 시작 위치. 정규식이 문자열의 처음부터 일치해야 함을 명시
    • (aya|ye|woo|ma) : 괄호는 하나의 단위로 처리. 넷 중 하나와 매칭
      • : (aya|ye|woo|ma) 패턴이 한 번 이상 나와야 함을 의미
    • $ : 문자열의 끝. 문자열의 끝까지 일치해야 함을 명시

Spring에서 Redis 사용하기

Repository 방식

  1. 의존성 설정
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-redis'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
  1. 설정파일 작성
spring:
  data:
    redis:
      host: localhost
      port: 6379
      username: <username>
      password: <비밀번호>
  1. Repository
public interface ItemRepository extends CrudRepository<Item, String> {

}
  1. 테스트
    테스트 코드로 데이터 삽입을 테스트해 보았다.
@SpringBootTest
public class RedisRepositoryTest {

    @Autowired
    private ItemRepository itemRepository;

    @Test
    public void createTest() {
        Item item = Item.builder()
                .name("keyboard")
                .description("too expensive")
                .price(2300091200)
                .build();
        itemRepository.save(item);
    }
}

테스트 성공, 데이터가 삽입되었음을 확인할 수 있다.
sets에는 생성된 id가, hash tables에는 id별로 데이터가 삽입된다.

id의 타입으로는 String으로 지정하면 자동으로 UUID를 생성해서 Id로 쓴다.
간단한 CRUD 작업은 위의 방법으로 쉽게 사용할 수 있다.

Redis Template 이용

  • 삽입/업데이트: set
  • 조회: get
  • 삭제: delete
  • 존재 확인: hasKey

ValueOperations

  • Spring Data Redis에서 제공하는 인터페이스
  • Redis의 String 자료구조를 쉽게 다룰 수 있도록 지원
  • ValueOperationsRedisTemplateopsForValue() 메서드를 통해 얻을 수 있음
  • RedisTemplate<String, Object>와 연계되어 Redis의 String 값을 처리
@SpringBootTest
public class RedisTemplateTests {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void stringOpsTest() {
        // ValueOperations<String, String>: String 조작을 위한 클래스
        // RedisTemplate에 설정된 타입을 바탕으로 Redis 문자열 조작
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        ops.set("key", "value");
        System.out.println(ops.get("key"));
    }
}

개인 과제로 MSA 프로젝트 구성을 하게 되었다.
프로젝트 구성 중 찾아본 것 정리

Spring Cloud Gateway와 Reactive Gateway

비교

특징Spring Cloud GatewayReactive Gateway
용도API Gateway의 전체 기능 제공Spring Cloud Gateway의 Reactive 모델 구성 요소
의존성spring-cloud-starter-gatewaySpring Cloud Gateway에 포함
Spring WebFlux 기반포함됨Reactive Streams 관련 기능을 지원함

결론
Spring Cloud Gateway만 추가하면 Reactive Gateway 기능도 자동 포함됨

profile
고민고민고민

0개의 댓글