애플리케이션 컨트롤러 코드는 다음과 같을 수 있다

 

    @PostMapping("/token")
    public ResponseEntity<JsonResult<AuthenticationResponseDto>> generateJwtToken
            (@RequestBody AuthenticationRequestDto authenticationRequestDto) {
        
        
        //bla bla ...
        
        if(!passwordEncoder.matches(authenticationRequestDto.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("Password not matched");
    	 }
         
         //bla bla ...
    }

 

이 코드에서 throw new BadCredentialsException("Password not matched"); 를 발생시키면 mockmvc 테스트 도중 NestedServletException 이 발생한다. 때문에 테스트를 실패하는데 junit5에서 다음과 같은 방법으로 NestedServletException 내부에서 발생한 exception을 검사할 수 있도록 다음과 같은 메서드를 제공한다.

 

 

org.assertj.core.api.Assertions.assertThatThrownBy(
	() -> mvc.perform(get("/api/scope")).andExpect(status().isOk()))
    .hasCause(new AccessDeniedException("Access is denied"));

 

이런식으로 테스트하면 테스트를 통과할 수 있다.

 

 

 

https://stackoverflow.com/questions/44900646/how-to-prevent-nestedservletexception-when-testing-spring-endpoints

 

How to prevent NestedServletException when testing Spring endpoints?

I am trying to test the security configuration of some of my endpoints which are secured with @PreAuthorize(#oauth2.hasScope('scope'). When accessing such an endpoint via Postman with a access toke...

stackoverflow.com

 

 

Netfilix Feign Client 테스트하는 방법이다.

 

github이슈에도 몇개 등록이 되어있는데 자세하게 읽어보지는 않았다.

 

 

 

 

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

@FeignClient(name = "authentication-service")
public interface AuthServiceClient {

    @PostMapping("/authenticate")
    Member getMember(String accessToken);

}

 

    @MockBean
    AuthServiceClient authServiceClient;
    
    
    
    ...
    
    
        @Test
        public void access_auth_user() throws Exception {
        
        
        ...
        
        
        Mockito.when(authServiceClient.getMember(accessToken)).thenReturn(member);

        ...
    }

 

일반적으로 Feign Client를 다음과같이 mocking하면 mock객체가아니라 실제 feign 구현체가 들어가서 테스트에 실패한다.

 

feign client를 mocking하는 방법은 아래와 같다

 

 

 

//primary 옵션을 false로 설정
@FeignClient(name = "authentication-service", primary = false)
public interface AuthServiceClient {

    @PostMapping("/authenticate")
    Member getMember(String accessToken);

}

 

    
    //test에서 선언시 name속성 추가
    @MockBean(name = "authServiceClient")
    AuthServiceClient authServiceClient;

 

 

이런식으로 테스트를 하면 mocking된 객체가 들어간다.

 

 

 

 

 

 

 

 

https://github.com/spring-cloud/spring-cloud-openfeign/issues/336

 

MockBean behaviour for Feign Clients change since Spring Boot 2.2.7 Release · Issue #336 · spring-cloud/spring-cloud-openfeign

Bug Versions: Spring Boot: 2.2.7 Spring Cloud: Hoxton.SR4 Before the Spring Boot 2.2.7 release, we used to create a Feign client (no fallback needed) and in certain situations we needed to create a...

github.com

 

 

 

 

 

----추가

 

추가적으로 슬라이스 테스트할때 Feign Client 객체를 autowired받는 방법이다.

@RestClientTest(MemberServiceClient.class)
@Import({RibbonAutoConfiguration.class,
        FeignRibbonClientAutoConfiguration.class,
        FeignAutoConfiguration.class})
class MemberServiceClientTest {

    @Autowired
    private MemberServiceClient client;
    
  
    //...tests  
  
  
}

 

https://github.com/spring-projects/spring-boot/issues/7270

 

이글은 Java(Spring) 개발자에게만 유용할 수 있습니다.

 

Redis에서 나같이 더미데이터를 넣어서 성능테스트를 해볼사람이 있을 수 있다..

 

Redis는 mass insert라는 api를 제공해서 데이터를 빠르게 넣을 수 있다

 

근데이게 자기네는 쉬운 api라고 소개하는데 대충 모양이

 

 

"*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n"

이런모양이다.

 

실제로도 그렇게 어려워보이진 않았지만 굳이 저걸 쓰고싶진 않았다..

 

자세한 정보는 아래에서 확인할 수 있다.

 

https://redis.io/topics/mass-insert

 

Redis Mass Insertion – Redis

*Redis Mass Insertion Sometimes Redis instances need to be loaded with a big amount of preexisting or user generated data in a short amount of time, so that millions of keys will be created as fast as possible. This is called a mass insertion, and the goal

redis.io

 

그래서 찾아낸 방법은 Jedis Client를 사용하는 방법이다.

 

Jedis Client는 pipeline api를 제공해주는데 사용방법은 아래와 같다

 

        try (Jedis jedis = new Jedis(redisHost, redisPort)) {
            Pipeline pipeline = jedis.pipelined();
            for (int i = 0; i < 7000000; i++) {

                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("name", "p" + i);

                hashMap.put("score", String.valueOf(i * (int)(Math.random() * 100) + 1));

                pipeline.zadd(KEY,  Double.parseDouble(hashMap.get("score")), hashMap.get("name"));
                pipeline.hset(KEY + ":" + hashMap.get("name"), hashMap);
            }

            pipeline.sync();
        }

 

 

 

이방법을 사용하면 약 700만개의 데이터가 1~2분 내외로 들어간다.

 

진짜 너무좋다 ..

 

메모리 생각 안하고 데이터를 꾸겨넣다보면 메모리가 금방 터지니 주의해야한다.

 

 

 

 

 

https://stackoverflow.com/questions/30728409/how-to-do-mass-insertion-in-redis-using-java

 

How to do Mass insertion in Redis using JAVA?

Hi I need to do multiple insertions of the form SADD key value I have the key value pair and needed to know how to perform mass insertions using JAVA . I have written a file in the Redis Protoco...

stackoverflow.com

 

 

ps 

 

lettuce도 비슷한 api가 있다!

 

https://github.com/lettuce-io/lettuce-core/wiki/Pipelining-and-command-flushing

 

lettuce-io/lettuce-core

Advanced Java Redis client for thread-safe sync, async, and reactive usage. Supports Cluster, Sentinel, Pipelining, and codecs. - lettuce-io/lettuce-core

github.com

 

lettuce는 비동기라그런지 뭔가 복잡하다

 

단발로 끝낼꺼면 jedis를 쓰자

 

 

이런 환경이 얼마나 있을지도 잘 모르겠지만

 

일단 현재 회사에서는 개발망이 따로 있기때문에 이 방법을 사용해야한다.

 

나와 같은 환경에 처한 사람들에게 유익한 정보가 되었으면 좋겠다!

 

 

먼저 진짜 생 offline 환경에서 docker hub를 접근해서 이미지를 땡겨오는건 진짜 말그대로 불가능이고

 

인터넷이 가능한 환경에서 image를 받아서 tar 파일로 압축한 뒤 해당 파일을 offline server에 ftp 같은 파일 전송 프로토콜을 사용해서 압축한 tar파일을 전송하고 그 tar파일을 docker image로 등록시킬수는 있다.

 

방법은 아래와 같다.

 

 

1.먼저 인터넷환경에서 받고싶은 image를 docker hub에서 땡겨받는다.

docker pull confluentinc/cp-kafka-connect:5.5.0

 

2.그리고 docker save 명령어로 이미지를 tar파일로 뺀다

 docker save confluentinc/cp-kafka-connect > confluent-kafka-connect-5.5.0.tar

 

3. tar파일을 offline server로 전송시키고 다음 명령어로 docker image에 등록한다

docker load < confluent-kafka-connect-5.5.0.tar

 

 

 

 

https://stackoverflow.com/questions/37905763/how-do-i-download-docker-images-without-using-the-pull-command

 

How do I download Docker images without using the pull command?

Is there a way I can download a Docker image/container using, for example, Firefox and not using the built-in docker-pull. I am blocked by the company firewall and proxy, and I can't get a hole th...

stackoverflow.com

 

 

 

 

 

아... 진짜 반나절 넘게 삽질했다

 

로그 설정좀 제대로 하고 할껄 ...ㅜㅜㅜ

 

class is not in the trusted packages 에러는 아마 intellij에서 producer랑 consumer를 모듈로 각각분리해서

 

entity도 개별적으로 존재? 하는 상황일 것이다 (consumer와 producer의 entity의 package fullname이 다를경우)

 

예를들어 producer쪽 entity의 package를 포함한 fullname이 zzz.xxx.producer.MyEntity 이고

 

consumer쪽 entity의 package를 포함한 fullname이 zzz.xxx.consumer.MyEntity 라면

 

consumer쪽의 JsonDeserializer에서 class is not in the trusted packages 에러를 뿜뿜할 것이다.

 

왜냐면 직렬화, 역직렬화에서는 package 이름까지 포함하기때문이다 ...

 

해결은 JsonDeserializer에 addTrustedPackages() 메서드를 수정하면 된다.

 

    @Bean
    public ConsumerFactory<String, GCMPushEntity> pushEntityConsumerFactory() {
        JsonDeserializer<GCMPushEntity> deserializer = new JsonDeserializer<>(GCMPushEntity.class);
        deserializer.setRemoveTypeHeaders(false);
        deserializer.addTrustedPackages("*");
        deserializer.setUseTypeMapperForKey(true);

        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserializer);
        return new DefaultKafkaConsumerFactory<>(
                props,
                new StringDeserializer(),
                deserializer);
    }

 

진짜 개삽질했다...

 

 

 

https://stackoverflow.com/questions/51688924/spring-kafka-the-class-is-not-in-the-trusted-packages

 

Spring Kafka The class is not in the trusted packages

In my Spring Boot/Kafka application before the library update, I used the following class org.telegram.telegrambots.api.objects.Update in order to post messages to the Kafka topic. Right now I use ...

stackoverflow.com

 

 

 

proxy_pass 설정중 난 에러 .. 

 

centos7, nginx1.16.1 기준으로 아래 명령어를 입력하면 proxy_pass가 잘 이뤄진다

 

setsebool -P httpd_can_network_connect 1

 

 

https://stackoverflow.com/questions/23948527/13-permission-denied-while-connecting-to-upstreamnginx

 

(13: Permission denied) while connecting to upstream:[nginx]

I am working with configuring Django project with Nginx and Gunicorn. While I am accessing my port gunicorn mysite.wsgi:application --bind=127.0.0.1:8001 in Nginx server, I am getting the following

stackoverflow.com

 

 

 

 

 

쿠버는 설치하고 클러스터 구성하는것도 너무 버겁다 ...

runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized 

 

위와 같은 에러가 떴다면

 

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

명령어 실행 후

 

systemctl restart kubelet

kubectl get nodes

 

로 상태를 확인하면 ...?

 

나는 잘 됐다

 

 

 

https://github.com/kubernetes/kubeadm/issues/1031

 

runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni conf

Is this a BUG REPORT or FEATURE REQUEST? BUG REPORT I've followed this guide. I've installed master node on 96 CPU ARM64 server. OS is Ubuntu 18.04 LTS. just after apt-get update/upgrade. U...

github.com

 

 

 

설정중에 만약 

 

No supported Kafka endpoints are configured. Either kafkastore.bootstrap.servers must have at least one endpoint matching kafkastore.security.protocol or broker endpoints loaded from ZooKeeper must have at least one endpoint matching kafkastore.security.protocol.

 

이런 에러가 떴다면 

 

 

kafkastore.bootstrap.servers=PLAINTEXT://localhost:9092, ...

 

이런식으로 설정하면 정상 동작한다 PLAINTEXT에 다른게 들어가야 하는줄 알았는데

 

진짜 그냥 PLAINTEXT가 들어가면 된다..

 

 

https://github.com/confluentinc/schema-registry/issues/765

 

 

 

 

 

 

+ Recent posts