사용자 정의 설정 전달하기

사용자 정의 설정 전달하기

SDK로 만든 함수를 실행하거나 갱신할 때, CLI의 --user-config 플래그로 함수에 임의의 키/값 쌍을 전달할 수 있어요. 키/값 쌍은 반드시 JSON으로 지정해야 해요.

함수는 이렇게 받은 설정을 컨텍스트 객체를 통해 읽어요. 예를 들어 "오늘의 단어" 같은 설정 값을 함수 안에서 꺼내 로그로 남기거나, 금지 단어처럼 함수 동작을 결정하는 값으로 쓸 수 있죠. 언어별로 접근 방법이 조금씩 다르니 하나씩 살펴볼게요.

알아두기: Java 함수에 전달되는 모든 키/값 쌍은 키와 값 모두 문자열이에요. 다른 타입으로 값을 설정하려면 문자열 타입에서 역직렬화(deserialize)해야 해요.

출처: 문서

본문

Java 함수에서 접근하기

Java SDK의 컨텍스트 객체는 CLI를 통해 (JSON으로) Pulsar 함수에 제공된 키/값 쌍에 접근하게 해줘요. 다음 예시는 키/값 쌍을 전달해요.

bin/pulsar-admin functions create \
  # Other function configs
  --user-config '{"word-of-the-day":"verdure"}'

Java 함수에서 그 값을 접근하려면:

import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
import org.slf4j.Logger;

import java.util.Optional;

public class UserConfigFunction implements Function<String, Void> {
    @Override
    public void apply(String input, Context context) {
        Logger LOG = context.getLogger();
        Optional<String> wotd = context.getUserConfigValue("word-of-the-day");
        if (wotd.isPresent()) {
            LOG.info("The word of the day is {}", wotd);
        } else {
            LOG.warn("No word of the day provided");
        }
        return null;
    }
}

UserConfigFunction은 함수가 호출될 때마다 "The word of the day is verdure" 문자열을 로그로 남겨요. word-of-the-day 설정은 CLI를 통해 함수를 새 값으로 갱신할 때만 바꿀 수 있어요.

전체 사용자 설정 맵에 접근하거나, 값이 없을 때 기본값을 설정할 수도 있어요.

// Get the whole config map
Map<String, String> allConfigs = context.getUserConfigMap();

// Get value or resort to default
String wotd = context.getUserConfigValueOrDefault("word-of-the-day", "perspicacious");

Python 함수에서 접근하기

Python 함수에서는 설정 값을 다음과 같이 접근할 수 있어요.

from pulsar import Function

class WordFilter(Function):
    def process(self, context, input):
        forbidden_word = context.user_config()["forbidden-word"]

        # Don't publish the message if it contains the user-supplied
        # forbidden word
        if forbidden_word in input:
            pass
        # Otherwise publish the message
        else:
            return input

Python SDK의 컨텍스트 객체는 명령줄을 통해 (JSON으로) 함수에 제공된 키/값 쌍에 접근하게 해줘요. 다음 예시는 키/값 쌍을 전달해요.

bin/pulsar-admin functions create \
  # Other function configs \
  --user-config '{"word-of-the-day":"verdure"}'

Python 함수에서 그 값을 접근하려면:

from pulsar import Function

class UserConfigFunction(Function):
    def process(self, input, context):
        logger = context.get_logger()
        wotd = context.get_user_config_value('word-of-the-day')
        if wotd is None:
            logger.warn('No word of the day provided')
        else:
            logger.info("The word of the day is {0}".format(wotd))

Go 함수에서 접근하기

Go SDK의 컨텍스트 객체는 명령줄을 통해 (JSON으로) 함수에 제공된 키/값 쌍에 접근하게 해줘요. 다음 예시는 키/값 쌍을 전달해요.

bin/pulsar-admin functions create \
  --go path/to/go/binary
  --user-config '{"word-of-the-day":"lackadaisical"}'

Go 함수에서 그 값을 접근하려면:

func contextFunc(ctx context.Context) {
  fc, ok := pf.FromContext(ctx)
  if !ok {
    logutil.Fatal("Function context is not defined")
  }

  wotd := fc.GetUserConfValue("word-of-the-day")

  if wotd == nil {
    logutil.Warn("The word of the day is empty")
  } else {
    logutil.Infof("The word of the day is %s", wotd.(string))
  }
}

더 알아보기 (Learn more)

  • 함수에 설정을 넘기는 다른 방법은 함수 배포 문서를 참고해요.
  • 컨텍스트 객체가 제공하는 전체 API가 궁금하다면 함수 개발 API 문서를 살펴보세요.
  • SDK로 함수를 개발하는 방법은 함수 개발 문서에서 확인할 수 있어요.