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   荣锋亮  阅读(31)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-01-02 nginx-clojure docker 镜像
2023-01-02 dremio NamespaceService 简单说明一
2023-01-02 dremio 的加速文件系统插件简单说明
2023-01-02 dremio ClassPathScanner 简单说明
2023-01-02 dremio formatPlugin 调用链
2023-01-02 gluon 基于浏览器+nodejs 的桌面应用开发框架
2022-01-02 ozone 为 apache hadoop 提供扩展分布式对象存储的服务

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示