Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

게임공장

GenServer 본문

Elixir

GenServer

짱승_ 2024. 3. 24. 22:33

GenServer 란?

  • 클라-서버 관계의 서버 구현 모듈
  • GenServer 는 다른 Elixir 프로세스와 동일한 프로세스이며 state 를 유지하고 비동기적으로 코드를 실행할 수 있다.
  • GenServer 를 사용해 구현된 서버는 규정된 인터페이스 함수들을 가지고 있으며 에러를 추적하고 리포트할 수 있는 기능을 가지고 있다. Supervision Tree(?) 에 적합함

구현 방법

  • 사용할 기능의 콜백 함수들만 구현하면 됨

Callback 함수들

  • init/1
    • 초기에 state 에 전달해줄 파라미터를 정의할 수 있다.
    • 필수로 구현되어야 하는 함수
@impl true
def init(elements) do
  initial_state = String.split(elements, ",", trim: true)
  {:ok, initial_state}
end
  • handle_call/3
    • 동기적으로 로직을 실행하고 결과를 송신측에 전달한다
@impl true
def handle_call(:pop, _from, state) do
  [to_caller | new_state] = state
  {:reply, to_caller, new_state}
end

GenServer.call(pid, :pop)
  • handle_cast/2
    • 비동기적으로 로직을 실행하고 결과를 송신측에 전달하지 않음
@impl true
def handle_cast({:push, element}, state) do
  new_state = [element | state]
  {:noreply, new_state}
end

GenServer.cast(pid, {:push, element})

서버 실행

{:ok, pid} = GenServer.start_link(Stack, "hello,world")

서버-클라 커뮤니케이션

반응형

'Elixir' 카테고리의 다른 글

ecto.rollback  (0) 2024.03.24