大网数据广告活动
服务器运维问答

Can HAProxy select a backend based on a lookup table?

· 52CE 我爱测

Let's say I have items A, B, and C. I have two backend servers: server01 and server02. Item A can be handled by server01, item B and C can be handled by server02. New items and servers get added and removed, and we programaticall…

问题原文

原帖链接 · kvz · CC BY-SA 4.0

Let's say I have items A, B, and C. I have two backend servers: server01 and server02.

Item A can be handled by server01, item B and C can be handled by server02. New items and servers get added and removed, and we programatically update a hash table between item id and backend server in a file, Redis, Memcache, or similar (whatever the proxy would support).

Can I make a frontend such as /items/${id}, and have HAProxy route to the correct backend server based on ${id}? So by looking up what id is associated with what server?

If not, would Nginx be able to do this?

社区高分解答

原帖链接 · GregL · CC BY-SA 3.0

You can use maps to make it work.

This is perfectly outlined in a post on the HAProxy.com blog. They're mapping based on the Host header, but it would be trivial to change the config to work for the URL.

One extra benefit here is that you can dynamically add and remove mapping entries using the http-[request|response] [set-map|del-map] keywords, or via the admin socket.
Changes made with http-[request|response]or via the socket aren't persisted between reboots, so you'd want to have some out of band process to update the map file at the same time, but that's another question all together.

Assuming you have a backend for each server, and given a map file called /etc/haproxy/items.map with these contents:

#itemPath    backendname
/item/a      bk_server01
/item/b      bk_server02
/item/c      bk_server02

You would do something like this in your frontend:

frontend ft_items
  [...]
  use_backend %[path,lower,map(/etc/haproxy/items.map,bk_default)]

If you have both servers in the same backend, you'd write an ACL in the front-end that catches all the items (acl items path_beg /items), send them to the backend (use_backend servers if items) and replace the use_backend line from the frontend with appropriately if-claused use_server lines in the backend.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-01-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0 / CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。