티스토리 뷰

이전 글에서 SEO 노출도를 올리기 위한 indexing API 작업을 했다.

 

그런데 문제가 있는게 indexing API는 하루에 200회의 제한이 있다.

https://developers.google.com/search/apis/indexing-api/v3/quota-pricing?hl=ko

 

api 콘솔 사이트를 들어가보면 사용량과 제한량을 볼 수 있다.

 

제한 횟수를 늘려달라고 요청할 수 있는데, 구글 친구들은 늘 그렇듯이 언제 해줄 수 있다고 알려주지 않는다.

 

그렇다고 한 개씩 등록하면(요청하면) HTTP 연결풀을 순간적으로 많이 잡아먹으니까 한번에 보낼 수 있는 방법을 만들어 뒀다.

 

일괄 색인 생성 요청 보내기라는 섹션을 만들어 둘 정도로 써달라고 만들어뒀는데...

 

이게 일단 예시를 바로 가져다 쓸 수 있게 생기질 않았다.

 

https://googleapis.github.io/google-api-java-client/batching.html

JsonBatchCallback<Calendar> callback = new JsonBatchCallback<Calendar>() {

  public void onSuccess(Calendar calendar, HttpHeaders responseHeaders) {
    printCalendar(calendar);
    addedCalendarsUsingBatch.add(calendar);
  }

  public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
    System.out.println("Error Message: " + e.getMessage());
  }
};

...

Calendar client = Calendar.builder(transport, jsonFactory, credential)
  .setApplicationName("BatchExample/1.0").build();
BatchRequest batch = client.batch();

Calendar entry1 = new Calendar().setSummary("Calendar for Testing 1");
client.calendars().insert(entry1).queue(batch, callback);

Calendar entry2 = new Calendar().setSummary("Calendar for Testing 2");
client.calendars().insert(entry2).queue(batch, callback);

batch.execute();

엄.... 일단 대충 어떻게 데이터를 만들어 보내야 된다는건 알겠는데...

 

어떤 라이브러리를 써야하나 헤더는 어떻게 만들어야하나 단하나도 정보가 없다...

 

다행히 스택오버플로우에 참고할만한 코드가 있었다.

https://stackoverflow.com/questions/54285181/google-indexing-api-request-batch-in-java

 

이걸 기반으로 만들 수 있었다.

public void googleWebSearchIndexingBatch(int page) {
    String endPoint = "https://indexing.googleapis.com/batch";

    url 생성 코드...
    List<String> urls = ...;

    try {
        InputStream keyFile = ResourceUtils.getURL("classpath:" + "indexing-api-sa.json")
                                           .openStream();

        GoogleCredentials credentials = GoogleCredentials.fromStream(keyFile)
                                                         .createScoped(Collections.singletonList(IndexingScopes.INDEXING));

        NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        JsonBatchCallback<PublishUrlNotificationResponse> callback = new JsonBatchCallback<PublishUrlNotificationResponse>() {
            public void onSuccess(PublishUrlNotificationResponse res, HttpHeaders responseHeaders) {
                try {
                    log.info("success : " + res.toPrettyString());
                } catch (IOException e) {
                    log.info("success : " + res.toString());
                }
            }

            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                log.error("Error Message: " + e.getMessage());
            }
        };

        Indexing client = new Indexing(transport, JSON_FACTORY, new HttpCredentialsAdapter(credentials));
        BatchRequest batch = client.batch();
        batch.setBatchUrl(new GenericUrl(endPoint));

        for (String url : urls) {
            UrlNotification unf = new UrlNotification();
            unf.setUrl(url);
            unf.setType("URL_UPDATED");
            client.urlNotifications().publish(unf).queue(batch, callback);
        }

        batch.execute();
    } catch (Exception e) {
        log.error("url indexing fail");
    }
    log.info("batch indexing 성공");
}

다행인건 credential을 발급받는 부분이 동일해서 헤더 구성이 바뀌지 않았다는 점이다.

 

그리고 client도 단일 indexing API와 동일했다.

 

Indexing 객체를 만들 수 있게 하는 라이브러리를 잘 찾는게 중요하다. 얘네는 왜 자기네들이 알려주질 않지..?

implementation 'com.google.apis:google-api-services-indexing:v3-rev20230927-2.0.0'

 

마치며

니네 레퍼런스보다 스택오버플로우가 낫다니.. 이게맞냐 구글아

 

개발자 사용성이 좋아야 이것저것 써보지 openAI 레퍼런스 보고 좀 배웠으면 좋겠다.

 

너네가 제공하는 것부터 정리가 안되는데 검색도 GPT한테 밀릴거같다 이젠

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함