oban简单学习试用

以前简单介绍过oban 一个强大的elixir任务框架,支持不少类型模式的job 处理,以下是一个简单的试用

环境准备

数据库使用了pg,oban 使用了ecto 这个强大的orm 框架,添加了oban 依赖之后就可以使用包含的mix ecto 命令进行
表的创建了,数据库使用docker-compose 运行

  • docker-compose.yaml
 
services:
  db:
    image: postgres:16.0
    ports:
      - "5432:5432"
    environment:
    - POSTGRES_PASSWORD=dalongdemo
  • 初始化oban
    创建supervisor mix 项目
 
mix new first --sup

添加依赖(包含了pg 以及oban)mix.exs

defp deps do
    [
        {:postgrex, "~> 0.17.4"},
        {:oban, "~> 2.16"}
    ]
end

创建ecto repo

mix ecto.gen.repo -r First.Repo

配置ecto

import Config
config :first,ecto_repos: [First.Repo]
 
config :first, First.Repo,
  database: "postgres",
  username: "postgres",
  password: "dalongdemo",
  hostname: "localhost"

ecto 创建oban 迁移任务

mix ecto.gen.migration add_oban_jobs_table

配置生成的迁移

defmodule First.Repo.Migrations.AddObanJobsTable do
  use Ecto.Migration
 
  def up do
    Oban.Migration.up(version: 11)
  end
 
  # We specify `version: 1` in `down`, ensuring that we'll roll all the way back down if
  # necessary, regardless of which version we've migrated `up` to.
  def down do
    Oban.Migration.down(version: 1)
  end
end

创建数据库表

mix ecto.migrate

效果

oban 运行配置
mix.exs

 
config :first, Oban,
  repo: First.Repo,
  plugins: [Oban.Plugins.Pruner],
  queues: [default: 10]

Supervisor 配置
lib/first/application.ex

 
@impl true
def start(_type, _args) do
    children = [
      First.Repo,
      {Oban, Application.fetch_env!(:first, Oban)}
    ]
    opts = [strategy: :one_for_one, name: First.Supervisor]
    Supervisor.start_link(children, opts)
end

检查配置,oban 提供了检查配置的方法,可以方便查看信息

iex -S mix
Oban.config()

效果

开发job任务

  • 简单任务
 
defmodule Job.Logjob do
  use Oban.Worker, queue: :logjob
  @impl Oban.Worker
  def perform(%Oban.Job{args: args}) do
    IO.inspect(args)
    :ok
  end
end
  • 执行任务
job = Job.Logjob.new(%{id: 1, params: []})
Oban.insert(job)

效果


启动队列(还是上边的执行shell 中)

 
Oban.start_queue(queue: :logjob, limit: 4)

效果

 

说明

oban 在elixir 的周边项目中使用还是很多的,值得学习下

参考资料

https://hexdocs.pm/oban/installation.html
https://getoban.pro/
https://github.com/sorentwo/oban
https://hexdocs.pm/oban/preparing_for_production.html
https://hexdocs.pm/oban/Oban.Config.html?ref=blixt-dev
https://github.com/elixir-ecto/ecto
https://hexdocs.pm/ecto/getting-started.html

posted on 2024-01-02 11:12  荣锋亮  阅读(15)  评论(0编辑  收藏  举报

导航