|
| 1 | +--- |
| 2 | +order: 5 |
| 3 | +--- |
| 4 | + |
| 5 | +# Available middlewares |
| 6 | + |
| 7 | +Middlewares allow you to execute code when specific event occurs. |
| 8 | +Taskiq has several default middlewares. |
| 9 | + |
| 10 | +### Simple retry middleware |
| 11 | + |
| 12 | +This middleware allows you to restart functions on errors. If exception was raised during task execution, |
| 13 | +the task would be resent with same parameters. |
| 14 | + |
| 15 | +To enable this middleware, add it to the list of middlewares for a broker. |
| 16 | + |
| 17 | +```python |
| 18 | +from taskiq import SimpleRetryMiddleware |
| 19 | + |
| 20 | +broker = ... |
| 21 | + |
| 22 | +broker.add_middlewares(SimpleRetryMiddleware(default_retry_count=3)) |
| 23 | +``` |
| 24 | + |
| 25 | +After that you can add a label to task that you want to restart on error. |
| 26 | + |
| 27 | +```python |
| 28 | + |
| 29 | +@broker.task(retry_on_error=True, max_retries=20) |
| 30 | +async def test(): |
| 31 | + raise Exception("AAAAA!") |
| 32 | + |
| 33 | +``` |
| 34 | + |
| 35 | +`retry_on_error` enables retries for a task. `max_retries` is the maximum number of times,. |
| 36 | + |
| 37 | +### Prometheus middleware |
| 38 | + |
| 39 | +You can enable prometheus metrics for workers by adding PrometheusMiddleware. |
| 40 | +To do so, you need to install `prometheus_client` package or you can install metrics extras for taskiq. |
| 41 | + |
| 42 | +::: tabs |
| 43 | + |
| 44 | + |
| 45 | +@tab only prometheus |
| 46 | + |
| 47 | +```bash |
| 48 | +pip install "prometheus_client" |
| 49 | +``` |
| 50 | + |
| 51 | +@tab taskiq with extras |
| 52 | + |
| 53 | +```bash |
| 54 | +pip install "taskiq[metrics]" |
| 55 | +``` |
| 56 | + |
| 57 | +::: |
| 58 | + |
| 59 | + |
| 60 | +```python |
| 61 | +from taskiq import PrometheusMiddleware |
| 62 | + |
| 63 | +broker = ... |
| 64 | + |
| 65 | +broker.add_middlewares(PrometheusMiddleware(server_addr="0.0.0.0", server_port=9000)) |
| 66 | +``` |
| 67 | + |
| 68 | +After that, metrics will be available at port 9000. Of course, this parameter can be configured. |
| 69 | +If you have other metrics, they'll be shown as well. |
0 commit comments