본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Kafka Consume: Lua 커스텀 필터 코드로 메시지 필터링

원문 보기 위키 갱신

이 문서에서는 Kafka Consume 플러그인에 Lua로 작성한 커스텀 필터 코드를 적용해서 메시지를 필터링하는 방법을 알려드려요, 예제에서는 값이 비어 있는 메시지를 걸러내도록 설정하고, decK, Admin API, Konnect API 세 가지 방식으로 플러그인을 구성하는 과정을 하나씩 살펴봐요, 시작하기 전에 Kafka 클러스터와 토픽이 준비되어 있는지도 꼭 확인해 보세요

출처: 문서

본문

Lua 커스텀 필터 코드로 메시지 필터링하기v3.12+

Kafka Consume 플러그인을 설정해서 Lua 커스텀 필터 코드로 메시지를 필터링해요. 이 예제에서는 Kafka Consume 플러그인이 빈 값을 기준으로 필터링해요.

사전 준비

환경 변수

  • BOOTSTRAP_SERVER_HOST: 부트스트랩 서버 호스트예요.

  • KAFKA_TOPIC: 메시지를 소비할 Kafka 토픽의 이름이에요.

플러그인 설정하기

전역(Global)

decK

다음 섹션을 kong.yaml 설정 파일에 추가하세요:

_format_version: "3.0"
plugins:
  - name: kafka-consume
    config:
      bootstrap_servers:
      - host: ${{ env "DECK_BOOTSTRAP_SERVER_HOST" }}
        port: 9092
      topics:
      - name: ${{ env "DECK_KAFKA_TOPIC" }}
      mode: server-sent-events
      message_by_lua_functions:
      - |
        return function(message)
          local m = type(message) == "table" and message or { value = message }
          if m.value == nil or (type(m.value)=="string" and #m.value==0) then
            return nil
          end
          return m
        end

{: data-file="kong.yaml" data-tool="deck" }

Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 바꾸세요:

  • region: Kong Konnect가 호스팅되고 운영되는 지리적 리전이에요.

  • KONNECT_TOKEN: Konnect 계정과 연결된 개인 액세스 토큰(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

리전별 URL과 개인 액세스 토큰에 대해 알아보려면 Konnect Control Planes Config API 레퍼런스를 참고하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongClusterPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
  labels:
    global: 'true'
config:
  bootstrap_servers:
  - host: '$BOOTSTRAP_SERVER_HOST'
    port: 9092
  topics:
  - name: '$KAFKA_TOPIC'
  mode: server-sent-events
  message_by_lua_functions:
  - |
    return function(message)
      local m = type(message) == 'table' and message or { value = message }
      if m.value == nil or (type(m.value)=='string' and #m.value==0) then
        return nil
      end
      return m
    end
plugin: kafka-consume
" | kubectl apply -f -
Terraform
사전 준비: 개인 액세스 토큰 설정하기
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect Gateway Plugin을 생성하려면 Terraform 설정에 다음 내용을 추가하세요:

resource "konnect_gateway_plugin_kafka_consume" "my_kafka_consume" {
  enabled = true

  config = {
    bootstrap_servers = [
      {
        host = var.bootstrap_server_host
        port = 9092
      }    ]
    topics = [
      {
        name = var.kafka_topic
      }    ]
    mode = "server-sent-events"
    message_by_lua_functions = [<<EOF
return function(message)
  local m = type(message) == "table" and message or { value = message }
  if m.value == nil or (type(m.value)=="string" and #m.value==0) then
    return nil
  end
  return m
end
EOF]
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
}

이 예제에서는 다음 변수들을 매니페스트에 추가해야 해요. TF_VAR_name=value 형식으로 설정하면 런타임에 값을 지정할 수 있어요.

variable "bootstrap_server_host" {
  type = string
}
variable "kafka_topic" {
  type = string
}

라우트(Route)

decK

다음 섹션을 kong.yaml 설정 파일에 추가하세요:

_format_version: "3.0"
plugins:
  - name: kafka-consume
    route: routeName|Id
    config:
      bootstrap_servers:
      - host: ${{ env "DECK_BOOTSTRAP_SERVER_HOST" }}
        port: 9092
      topics:
      - name: ${{ env "DECK_KAFKA_TOPIC" }}
      mode: server-sent-events
      message_by_lua_functions:
      - |
        return function(message)
          local m = type(message) == "table" and message or { value = message }
          if m.value == nil or (type(m.value)=="string" and #m.value==0) then
            return nil
          end
          return m
        end

{: data-file="kong.yaml" data-tool="deck" }

다음 플레이스홀더는 반드시 여러분의 값으로 바꾸세요:

  • routeName|Id: 플러그인 설정이 적용될 라우트의 id 또는 name이에요.
Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/routes/{routeName|Id}/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 바꾸세요:

  • routeName|Id: 플러그인 설정이 적용될 라우트의 id 또는 name이에요.
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/routes/{routeId}/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 바꾸세요:

  • region: Kong Konnect가 호스팅되고 운영되는 지리적 리전이에요.

  • KONNECT_TOKEN: Konnect 계정과 연결된 개인 액세스 토큰(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

  • routeId: 플러그인 설정이 적용될 라우트의 id예요.

리전별 URL과 개인 액세스 토큰에 대해 알아보려면 Konnect Control Planes Config API 레퍼런스를 참고하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  bootstrap_servers:
  - host: '$BOOTSTRAP_SERVER_HOST'
    port: 9092
  topics:
  - name: '$KAFKA_TOPIC'
  mode: server-sent-events
  message_by_lua_functions:
  - |
    return function(message)
      local m = type(message) == 'table' and message or { value = message }
      if m.value == nil or (type(m.value)=='string' and #m.value==0) then
        return nil
      end
      return m
    end
plugin: kafka-consume
" | kubectl apply -f -

다음으로, httproute 또는 ingress 리소스에 어노테이션을 붙여서 KongPlugin 리소스를 적용하세요:

Gateway API
kubectl annotate -n kong httproute  konghq.com/plugins=
Ingress
kubectl annotate -n kong ingress  konghq.com/plugins=
Terraform
사전 준비: 개인 액세스 토큰 설정하기
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect Gateway Plugin을 생성하려면 Terraform 설정에 다음 내용을 추가하세요:

resource "konnect_gateway_plugin_kafka_consume" "my_kafka_consume" {
  enabled = true

  config = {
    bootstrap_servers = [
      {
        host = var.bootstrap_server_host
        port = 9092
      }    ]
    topics = [
      {
        name = var.kafka_topic
      }    ]
    mode = "server-sent-events"
    message_by_lua_functions = [<<EOF
return function(message)
  local m = type(message) == "table" and message or { value = message }
  if m.value == nil or (type(m.value)=="string" and #m.value==0) then
    return nil
  end
  return m
end
EOF]
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
  route = {
    id = konnect_gateway_route.my_route.id
  }
}

이 예제에서는 다음 변수들을 매니페스트에 추가해야 해요. TF_VAR_name=value 형식으로 설정하면 런타임에 값을 지정할 수 있어요.

variable "bootstrap_server_host" {
  type = string
}
variable "kafka_topic" {
  type = string
}

컨슈머(Consumer)

decK

다음 섹션을 kong.yaml 설정 파일에 추가하세요:

_format_version: "3.0"
plugins:
  - name: kafka-consume
    consumer: consumerName|Id
    config:
      bootstrap_servers:
      - host: ${{ env "DECK_BOOTSTRAP_SERVER_HOST" }}
        port: 9092
      topics:
      - name: ${{ env "DECK_KAFKA_TOPIC" }}
      mode: server-sent-events
      message_by_lua_functions:
      - |
        return function(message)
          local m = type(message) == "table" and message or { value = message }
          if m.value == nil or (type(m.value)=="string" and #m.value==0) then
            return nil
          end
          return m
        end

{: data-file="kong.yaml" data-tool="deck" }

다음 플레이스홀더는 반드시 여러분의 값으로 바꾸세요:

  • consumerName|Id: 플러그인 설정이 적용될 컨슈머의 id 또는 name이에요.
Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/consumers/{consumerName|Id}/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '

다음 플레이스홀더를 여러분의 값으로 바꿔야 해요:

  • consumerName|Id: 플러그인 구성이 대상으로 삼을 컨슈머의 id 또는 name이에요.
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/consumers/{consumerId}/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "kafka-consume",
      "config": {
        "bootstrap_servers": [
          {
            "host": "'$BOOTSTRAP_SERVER_HOST'",
            "port": 9092
          }
        ],
        "topics": [
          {
            "name": "'$KAFKA_TOPIC'"
          }
        ],
        "mode": "server-sent-events",
        "message_by_lua_functions": [
          "return function(message)\n  local m = type(message) == \"table\" and message or { value = message }\n  if m.value == nil or (type(m.value)==\"string\" and #m.value==0) then\n    return nil\n  end\n  return m\nend\n"
        ]
      }
    }
    '

다음 플레이스홀더를 여러분의 값으로 바꿔야 해요:

  • region: 여러분의 Kong Konnect가 호스팅되고 동작하는 지리적 지역이에요.

  • KONNECT_TOKEN: Konnect 계정과 연결된 개인 액세스 토큰(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

  • consumerId: 플러그인 구성이 대상으로 삼을 컨슈머의 id예요.

지역별 URL과 개인 액세스 토큰에 대해 알아보려면 Konnect Control Planes Config API 레퍼런스를 확인하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  bootstrap_servers:
  - host: '$BOOTSTRAP_SERVER_HOST'
    port: 9092
  topics:
  - name: '$KAFKA_TOPIC'
  mode: server-sent-events
  message_by_lua_functions:
  - |
    return function(message)
      local m = type(message) == 'table' and message or { value = message }
      if m.value == nil or (type(m.value)=='string' and #m.value==0) then
        return nil
      end
      return m
    end
plugin: kafka-consume
" | kubectl apply -f -

다음으로, KongConsumer 리소스에 어노테이션을 붙여서 KongPlugin 리소스를 적용하세요:

kubectl annotate -n kong kongconsumer CONSUMER_NAME konghq.com/plugins=
Terraform
사전 준비: 개인 액세스 토큰 구성하기
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect 게이트웨이 플러그인을 생성하려면 Terraform 구성에 다음 내용을 추가하세요:

resource "konnect_gateway_plugin_kafka_consume" "my_kafka_consume" {
  enabled = true

  config = {
    bootstrap_servers = [
      {
        host = var.bootstrap_server_host
        port = 9092
      }    ]
    topics = [
      {
        name = var.kafka_topic
      }    ]
    mode = "server-sent-events"
    message_by_lua_functions = [<<EOF
return function(message)
  local m = type(message) == "table" and message or { value = message }
  if m.value == nil or (type(m.value)=="string" and #m.value==0) then
    return nil
  end
  return m
end
EOF]
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
  consumer = {
    id = konnect_gateway_consumer.my_consumer.id
  }
}

이 예제에서는 매니페스트에 다음 변수들을 추가해야 해요. TF_VAR_name=value 형식으로 값을 설정하면 런타임에 값을 지정할 수 있어요.

variable "bootstrap_server_host" {
  type = string
}
variable "kafka_topic" {
  type = string
}

관련 리소스

더 알아보기 (Learn more)

  • decK 설정 파일 kong.yaml를 작성하는 기본 방법을 먼저 익혀 두면 좋아요 — kong.yaml
  • Konnect API로 플러그인을 설정할 때 참고할 수 있는 Control Planes Config API 문서예요 — Konnect Control Planes Config API reference
  • Kafka로 로그를 전송하는 Kafka Log 플러그인의 사용 방법도 함께 확인해 보세요 — Kafka Log plugin
  • Kafka Upstream 플러그인으로 Kafka 클러스터와 연동하는 방법을 살펴봐요 — Kafka Upstream plugin
  • Confluent에서 메시지를 소비하는 Confluent Consume 플러그인도 참고할 만해요 — Confluent Consume plugin