Redis FDW(Foreign Data Wrapper)为Dave&Andrew实现的Postgresql的FDW扩展插件,可以直接在postgresql里访问redis数据库,支持Posgreql9.1~9.6。
1、安装
系统环境:Fedora25 / postgresql9.5.5 / redis3.0.6 (postgresql&redis均通过dnf安装)
1) 根据个人postgresql版本的clone对应的分支代码:git clone -b REL9_5_STABLE git@github.com:pg-redis-fdw/redis_fdw.git
2) 编译安装:
- cd redis_fdw/
- make USE_PGXS=1
- make USE_PGXS=1 install
/usr/lib/rpm/redhat/redhat-hardened-cc1 No that file and directory,运行dnf install redhat-rpm-config -y即可。
OK,安装完成。
2、实验
categories
记录不同分类下条目的数量:
1. CREATE TABLE categories
2. (
3. catid character varying(32) NOT NULL, --主键
4. cname character varying(64), --分类名称
5. nums integer, --条目数量
6. CONSTRAINT categories_pkey PRIMARY KEY (catid)
7. )
catid--->nums
映射。
准备工作:
1. postgres=# CREATE EXTENSION redis_fdw; --创建redis_fdw扩展
2. 3. postgres=# \dx
4. List of installed extensions
5. Name | Version | Schema | Description
6. -----------+---------+------------+--------------------------------------------------
7. redis_fdw | 1.0 | public | Foreign data wrapper for querying a Redis server
8. 9. -- 创建需要关联的redis服务器
10. postgres=# CREATE SERVER redis_server
11. FOREIGN DATA WRAPPER redis_fdw
12. OPTIONS (address '127.0.0.1', port '6379');
13. 14. postgres=# \des
15. List of foreign servers
16. Name | Owner | Foreign-data wrapper
17. --------------+----------+----------------------
18. redis_server | postgres | redis_fdw
19. 20. --创建redis中存储catid/nums映射的虚拟表
21. postgres=# CREATE FOREIGN TABLE rd_categories (key text, val text)
22. SERVER redis_server
23. OPTIONS (database '0');
24. 25. postgres=# \d
26. List of relations
27. Schema | Name | Type | Owner
28. --------+---------------+---------------+----------
29. public | categories | table | postgres
30. public | rd_categories | foreign table | postgres
创建触发器:
1. CREATE OR REPLACE FUNCTION public.insert_new_item()
2. RETURNS trigger AS
3. $BODY$
4. begin
5. insert into rd_categories values(NEW.catid, 0);
6. return NEW;
7. end
8. $BODY$
9. LANGUAGE plpgsql VOLATILE
10. COST 100;
11. ALTER FUNCTION public.insert_new_item()
12. OWNER TO postgres;
13. 14. CREATE TRIGGER new_category
15. AFTER INSERT
16. ON public.categories
17. FOR EACH ROW
18. EXECUTE PROCEDURE public.insert_new_item();
测试:
insert into categories values('123', 'ces', 0); --插入一条数据
在redis里查看:
[root@w1 redis_fdw]# redis-cli127.0.0.1:6379> keys *1) "123"127.0.0.1:6379> get 123"0"