question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
How to know status of redis from command line (redis-cli) ? master/slave
The INFO command returns the current role. e.g/ if we're the master role:master will be shown, amongst other details. And if we switch to a slave, maybe by using slaveof: slaveof 192.168.1.66 6379 We get more, when we run INFO: role:slave master_host:192.168.1.66 master_port:6379 master_link_status:down master_last_io_seconds_ago:-1 master_sync_in_progress:0 master_link_down_since_seconds:1341313174 EDIT: Here's a succinct cli command as shown by Linus (but who's just deleted his post): redis-cli info | grep ^role :)
Redis
11,307,356
51
In official docs we can see: # docker build github.com/creack/docker-firefox It just works fine to me. docker-firefox is a repository and has Dockerfile within root dir. Then I want to buid redis image and exact version 2.8.10 : # docker build github.com/docker-library/redis/tree/99c172e82ed81af441e13dd48dda2729e19493bc/2.8.10 2014/11/05 16:20:32 Error trying to use git: exit status 128 (Initialized empty Git repository in /tmp/docker-build-git067001920/.git/ error: The requested URL returned error: 403 while accessing https://github.com/docker-library/redis/tree/99c172e82ed81af441e13dd48dda2729e19493bc/2.8.10/info/refs fatal: HTTP request failed ) I got error above. What's the right format with build docker image from github repos?
docker build url#ref:dir where ref is a branch, a tag, or a commit SHA. Git URLs accept context configuration in their fragment section, separated by a colon :. The first part represents the reference that Git will check out, this can be either a branch, a tag, or a commit SHA. The second part represents a subdirectory inside the repository that will be used as a build context. For example, run this command to use a directory called docker in the branch container: docker build https://github.com/docker/rootfs.git#container:docker https://docs.docker.com/engine/reference/commandline/build/
Redis
26,753,030
50
I have a redis server 2.8 installed using ubuntu apt-get on ubuntu 12.04. I have copied a dump.rdb from an other database. Now when I try to start the new server, I constantly get: [35763] 04 Mar 01:51:47.088 * 1 changes in 900 seconds. Saving... [35763] 04 Mar 01:51:47.088 * Background saving started by pid 43313 [43313] 04 Mar 01:51:47.088 # Failed opening .rdb for saving: Permission denied How can I solve this?
You should check your redis.conf file to see the permissions in dir and dbfilename. If the file named in the dbfilename which is located in the path specified in the dir path exists and the permission is also right. then the problem should be fixed. Hope this will help someone. P.S. To find the redis.conf file location, you can use the #ps ax | grep redis to check. Usually it will be passed to the redis-server as input file. For the dir permissions:it should be 755, for the dbfilename, it should be 644 Sometimes you also need to use top command to check whether the user:group of the redis-server and the owner of dir are consistent. i.e. The redis-server is running by redis:redis, but the dir is under root:root. In this case, you need to chown redis:redis -R dir.
Redis
22,160,753
50
I am trying to integrate Redis sessions into my authentication system written in Node.js. I have been able to successfully set up Redis server, connect-redis and Express server. Here is my setup (just the important bit): var express = require("express"); var RedisStore = require("connect-redis")(express); var redis = require("redis").createClient(); app.use(express.cookieParser()); app.use(express.session({ secret: "thisismysecretkey", store: new RedisStore({ host: 'localhost', port: 6379, client: redis }) })); Now... How do I actually create, read and destroy the session? I am aware that that is probably extremely simple. I have read tons of articles on how to setup connect-redis and many questions here on SO, but I swear each one stops on just the configuration and does not explain how to actually use it...
That should be all there is to it. You access the session in your route handlers via req.session. The sessions are created, saved, and destroyed automatically. If you need to manually create a new session for a user, call req.session.regenerate(). If you need to save it manually, you can call req.session.save(). If you need to destroy it manually, you can call req.session.destroy(). See the Connect documentation for the full list of methods and properties.
Redis
14,014,446
50
I have 2 services. Both of them need subscribe to the same channel. The 2 services are load balanced. Each service runs on multiple servers. So how can I be sure only 1 instance of each service consume the message of that channel. Is this supported on Redis? Thanks
Pubsub doesn't work that way - the message goes to all connected subscribed clients. However, you could set it up so that the channel is a notification of an update to a list. That way all clients will get the message, but only one can take the item from the list with LPOP.
Redis
7,196,306
50
I want to be able to delete all the keys. Is there a way to flush all in node redis? Redis client: client = redis.createClient(REDIS_PORT, REDIS_HOST);
Perhaps flushdb or flushall are options that you can look into. In Node, with the client, these look like this: client.flushdb( function (err, succeeded) { console.log(succeeded); // will be true if successfull });
Redis
37,866,554
49
I have a question - lookup of a key value pair in an index - let's say on cassandra or postgres - is typically at around O(logn) source: https://github.com/tinkerpop/blueprints/wiki/Graph-Indices. In the redis documentation it states that runtime complexity is O(1). Source: http://redis.io/commands/get http://redis.io/commands/hget And getting the value of multiple keys is only linear O(m) where m is the number of keys retrieved http://redis.io/commands/hmget How is it possible?
Redis is an in-memory store. It can therefore use data structures which are adapted to memory storage (allowing for fast random access). To implement dictionaries (used for the main dictionary, but also for hash and set objects, and in conjunction with a skip list for zset objects), Redis use separate chaining hash tables, whose access complexity is O(1+n/k) where n is the number of items and k the number of buckets. Redis makes sure the number of buckets grows with the number of items so that in practice n/k is kept low. This rehashing activity is done incrementally in background. When the number of items is significant, the complexity is close to O(1) (amortized). Other stores (Cassandra for instance) are designed to store data on disk while minimizing the number of random I/Os for performance reasons. A hash table is not a good data structure for this, because it does not enforce the locality of the data (it does not benefit from buffer caching very well). So disk based stores usually use B-tree variants (most RDBMS) or log-structured merge (LSM) trees variants (Cassandra), which have O(log n) complexity. So yes, Redis offers O(1) for many operations, but there is a constraint: all data should fit in memory. There is no magic here.
Redis
15,216,897
49
Why does Redis use integer database numbers instead of strings? It seems like it would be trivial to keep a small internal data structure which maps strings to the “actual” integer.
the reason why Redis does not use strings as DB names but indexes is that the goal and ability of Redis databases is not to provide an outer level of dictionary: Redis dictionaries can't scale to many dictionaries, but just to a small number (it is a tradeoff), nor we want to provide nested data structures per design, so this are just "a few namespaces" and as a result using a numerical small index seemed like the best option.
Redis
6,618,291
49
Leveldb seems to be a new interesting persistent key value store from Google. How does Leveldb differ from Redis or Riak or Tokyo Tyrant? In what specific use cases is one better than the other?
I only add this because in both of the previous answers I don't see this (important) distinction made... Redis: Is a database server. You communicate with it via a custom binary protocol (via client library typically). LevelDB: Is a library that implements a key-value store. You communicate with it by calling the C++ API directly. If you are familiar with SQLite and how popular it has become as an embedded DB for client applications (I believe both Android and iOS ship it) then you see where something like LevelDB fits in. Imagine you were writing a complex PIM app, maybe some enterprise address book manager meant to be installed on individual computers in the office. You wouldn't want to store all that data in XML or JSON that you wrote/parsed yourself inside your app -- if you could, you'd much rather store it in a DB to have easier access patterns. But you also don't want to have to ship and install a local copy of Redis, running on some random port just so you can connect to it... you want a DB that you can call directly and natively from your app and not worry about "over the wire" communication... you want the raw guts of a DB without any of the network-ey stuff that you don't need in a client only app. This is where LevelDB sits. It is a different tool for a different job.
Redis
6,101,402
49
Setup: I have a virtual machine and in the virtual machine running three containers (an nginx proxy, a very minimalistic flask app and redis). Flask should be serving on port 5000 while redis on 6379. Each of these containers are up and running just fine as stand a lone services, but also available via docker compose as a service. In the flask app, my aim is to connect to redis and query for some keys. The nginx container exposes port 80, flask port 5000 and redis port 6379. In the flask app I have a function that tries to create a redis client db = redis.Redis(host='localhost', port=6379, decode_responses=True) Running the flask app I am getting an error that the port cannot be used redis.exceptions.ConnectionError: Error 99 connecting to localhost:6379. Cannot assign requested address. I am lost of clarity what could be causing this problem and any ideas would be appreciated.
In the flask app I have a function that tries to create a redis client db = redis.Redis(host='localhost', port=6379, decode_responses=True) When your flask process runs in a container, localhost refers to the network interface of the container itself. It does not resolve to the network interface of your docker host. So you need to replace localhost with the IP address of the container running redis. In the context of a docker-compose.yml file, this is easy as docker-compose will make service names resolve to the correct container IP address: version: "3" services: my_flask_service: image: ... my_redis_service: image: ... then in your flask app, use: db = redis.Redis(host='my_redis_service', port=6379, decode_responses=True)
Redis
54,965,291
48
The Redis startup script is supposed to create a pid file at startup, but I've confirmed all the settings I can find, and no pid file is ever created. I installed redis by: $ yum install redis $ chkconfig redis on $ service redis start In my config file (/etc/redis.conf) I checked to make sure these were enabled: daemonize yes pidfile /var/run/redis/redis.pid And in the startup script (/etc/init.d/redis) there is: exec="/usr/sbin/$name" pidfile="/var/run/redis/redis.pid" REDIS_CONFIG="/etc/redis.conf" [ -e /etc/sysconfig/redis ] && . /etc/sysconfig/redis lockfile=/var/lock/subsys/redis start() { [ -f $REDIS_CONFIG ] || exit 6 [ -x $exec ] || exit 5 echo -n $"Starting $name: " daemon --user ${REDIS_USER-redis} "$exec $REDIS_CONFIG" retval=$? echo [ $retval -eq 0 ] && touch $lockfile return $retval } stop() { echo -n $"Stopping $name: " killproc -p $pidfile $name retval=$? echo [ $retval -eq 0 ] && rm -f $lockfile return $retval } These are the settings that came by default with the install. Any idea why no pid file is created? I need to use it for Monit. (The system is RHEL 6.4 btw)
For those experiencing on Debian buster: Editing nano /etc/systemd/system/redis.service and adding this line below redis [Service] ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid" It suppose to look like this: [Service] Type=forking ExecStart=/usr/bin/redis-server /etc/redis/redis.conf ExecStop=/bin/kill -s TERM $MAINPID ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid" PIDFile=/run/redis/redis-server.pid then: sudo systemctl daemon-reload sudo systemctl restart redis.service Check redis.service status: sudo systemctl status redis.service The pid file now should appear.
Redis
25,515,166
48
I wanted to create a redis cache in python, and as any self respecting scientist I made a bench mark to test the performance. Interestingly, redis did not fare so well. Either Python is doing something magic (storing the file) or my version of redis is stupendously slow. I don't know if this is because of the way my code is structured, or what, but I was expecting redis to do better than it did. To make a redis cache, I set my binary data (in this case, an HTML page) to a key derived from the filename with an expiration of 5 minutes. In all cases, file handling is done with f.read() (this is ~3x faster than f.readlines(), and I need the binary blob). Is there something I'm missing in my comparison, or is Redis really no match for a disk? Is Python caching the file somewhere, and reaccessing it every time? Why is this so much faster than access to redis? I'm using redis 2.8, python 2.7, and redis-py, all on a 64 bit Ubuntu system. I do not think Python is doing anything particularly magical, as I made a function that stored the file data in a python object and yielded it forever. I have four function calls that I grouped: Reading the file X times A function that is called to see if redis object is still in memory, load it, or cache new file (single and multiple redis instances). A function that creates a generator that yields the result from the redis database (with single and multi instances of redis). and finally, storing the file in memory and yielding it forever. import redis import time def load_file(fp, fpKey, r, expiry): with open(fp, "rb") as f: data = f.read() p = r.pipeline() p.set(fpKey, data) p.expire(fpKey, expiry) p.execute() return data def cache_or_get_gen(fp, expiry=300, r=redis.Redis(db=5)): fpKey = "cached:"+fp while True: yield load_file(fp, fpKey, r, expiry) t = time.time() while time.time() - t - expiry < 0: yield r.get(fpKey) def cache_or_get(fp, expiry=300, r=redis.Redis(db=5)): fpKey = "cached:"+fp if r.exists(fpKey): return r.get(fpKey) else: with open(fp, "rb") as f: data = f.read() p = r.pipeline() p.set(fpKey, data) p.expire(fpKey, expiry) p.execute() return data def mem_cache(fp): with open(fp, "rb") as f: data = f.readlines() while True: yield data def stressTest(fp, trials = 10000): # Read the file x number of times a = time.time() for x in range(trials): with open(fp, "rb") as f: data = f.read() b = time.time() readAvg = trials/(b-a) # Generator version # Read the file, cache it, read it with a new instance each time a = time.time() gen = cache_or_get_gen(fp) for x in range(trials): data = next(gen) b = time.time() cachedAvgGen = trials/(b-a) # Read file, cache it, pass in redis instance each time a = time.time() r = redis.Redis(db=6) gen = cache_or_get_gen(fp, r=r) for x in range(trials): data = next(gen) b = time.time() inCachedAvgGen = trials/(b-a) # Non generator version # Read the file, cache it, read it with a new instance each time a = time.time() for x in range(trials): data = cache_or_get(fp) b = time.time() cachedAvg = trials/(b-a) # Read file, cache it, pass in redis instance each time a = time.time() r = redis.Redis(db=6) for x in range(trials): data = cache_or_get(fp, r=r) b = time.time() inCachedAvg = trials/(b-a) # Read file, cache it in python object a = time.time() for x in range(trials): data = mem_cache(fp) b = time.time() memCachedAvg = trials/(b-a) print "\n%s file reads: %.2f reads/second\n" %(trials, readAvg) print "Yielding from generators for data:" print "multi redis instance: %.2f reads/second (%.2f percent)" %(cachedAvgGen, (100*(cachedAvgGen-readAvg)/(readAvg))) print "single redis instance: %.2f reads/second (%.2f percent)" %(inCachedAvgGen, (100*(inCachedAvgGen-readAvg)/(readAvg))) print "Function calls to get data:" print "multi redis instance: %.2f reads/second (%.2f percent)" %(cachedAvg, (100*(cachedAvg-readAvg)/(readAvg))) print "single redis instance: %.2f reads/second (%.2f percent)" %(inCachedAvg, (100*(inCachedAvg-readAvg)/(readAvg))) print "python cached object: %.2f reads/second (%.2f percent)" %(memCachedAvg, (100*(memCachedAvg-readAvg)/(readAvg))) if __name__ == "__main__": fileToRead = "templates/index.html" stressTest(fileToRead) And now the results: 10000 file reads: 30971.94 reads/second Yielding from generators for data: multi redis instance: 8489.28 reads/second (-72.59 percent) single redis instance: 8801.73 reads/second (-71.58 percent) Function calls to get data: multi redis instance: 5396.81 reads/second (-82.58 percent) single redis instance: 5419.19 reads/second (-82.50 percent) python cached object: 1522765.03 reads/second (4816.60 percent) The results are interesting in that a) generators are faster than calling functions each time, b) redis is slower than reading from the disk, and c) reading from python objects is ridiculously fast. Why would reading from a disk be so much faster than reading from an in-memory file from redis? EDIT: Some more information and tests. I replaced the function to data = r.get(fpKey) if data: return r.get(fpKey) The results do not differ much from if r.exists(fpKey): data = r.get(fpKey) Function calls to get data using r.exists as test multi redis instance: 5320.51 reads/second (-82.34 percent) single redis instance: 5308.33 reads/second (-82.38 percent) python cached object: 1494123.68 reads/second (5348.17 percent) Function calls to get data using if data as test multi redis instance: 8540.91 reads/second (-71.25 percent) single redis instance: 7888.24 reads/second (-73.45 percent) python cached object: 1520226.17 reads/second (5132.01 percent) Creating a new redis instance on each function call actually does not have a noticable affect on read speed, the variability from test to test is larger than the gain. Sripathi Krishnan suggested implementing random file reads. This is where caching starts to really help, as we can see from these results. Total number of files: 700 10000 file reads: 274.28 reads/second Yielding from generators for data: multi redis instance: 15393.30 reads/second (5512.32 percent) single redis instance: 13228.62 reads/second (4723.09 percent) Function calls to get data: multi redis instance: 11213.54 reads/second (3988.40 percent) single redis instance: 14420.15 reads/second (5157.52 percent) python cached object: 607649.98 reads/second (221446.26 percent) There is a HUGE amount of variability in file reads so the percent difference is not a good indicator of speedup. Total number of files: 700 40000 file reads: 1168.23 reads/second Yielding from generators for data: multi redis instance: 14900.80 reads/second (1175.50 percent) single redis instance: 14318.28 reads/second (1125.64 percent) Function calls to get data: multi redis instance: 13563.36 reads/second (1061.02 percent) single redis instance: 13486.05 reads/second (1054.40 percent) python cached object: 587785.35 reads/second (50214.25 percent) I used random.choice(fileList) to randomly select a new file on each pass through the functions. The full gist is here if anyone would like to try it out - https://gist.github.com/3885957 Edit edit: Did not realize that I was calling one single file for the generators (although the performance of the function call and generator was very similar). Here is the result of different files from the generator as well. Total number of files: 700 10000 file reads: 284.48 reads/second Yielding from generators for data: single redis instance: 11627.56 reads/second (3987.36 percent) Function calls to get data: single redis instance: 14615.83 reads/second (5037.81 percent) python cached object: 580285.56 reads/second (203884.21 percent)
This is an apples to oranges comparison. See http://redis.io/topics/benchmarks Redis is an efficient remote data store. Each time a command is executed on Redis, a message is sent to the Redis server, and if the client is synchronous, it blocks waiting for the reply. So beyond the cost of the command itself, you will pay for a network roundtrip or an IPC. On modern hardware, network roundtrips or IPCs are suprisingly expensive compared to other operations. This is due to several factors: the raw latency of the medium (mainly for network) the latency of the operating system scheduler (not guaranteed on Linux/Unix) memory cache misses are expensive, and the probability of cache misses increases while the client and server processes are scheduled in/out. on high-end boxes, NUMA side effects Now, let's review the results. Comparing the implementation using generators and the one using function calls, they do not generate the same number of roundtrips to Redis. With the generator you simply have: while time.time() - t - expiry < 0: yield r.get(fpKey) So 1 roundtrip per iteration. With the function, you have: if r.exists(fpKey): return r.get(fpKey) So 2 roundtrips per iteration. No wonder the generator is faster. Of course you are supposed to reuse the same Redis connection for optimal performance. There is no point to run a benchmark which systematically connects/disconnects. Finally, regarding the performance difference between Redis calls and the file reads, you are simply comparing a local call to a remote one. File reads are cached by the OS filesystem, so they are fast memory transfer operations between the kernel and Python. There is no disk I/O involved here. With Redis, you have to pay for the cost of the roundtrips, so it is much slower.
Redis
12,868,222
48
Somebody asked me what PubSub was and how to create a channel (in comment from my answer) and I pointed him to the article on redis.io => http://redis.io/topics/pubsub. I think it is pretty clear, but I am wondering if somebody has a better explanation. Ideally, describe it clearly using redis-cli.
Publish/subscribe is a pretty simple paradigm. Think of it like you're running a talk show on a radio station. That's PUBLISH. You're hoping at least one or more people will pick up your channel to listen to your messages on the radio show (SUBSCRIBE) and maybe even do some stuff, but you're not talking to folks directly. Let's have some fun with redis-cli! redis 127.0.0.1:6379> PUBLISH myradioshow "Good morning everyone!" (integer) 0 redis 127.0.0.1:6379> PUBLISH myradioshow "How ya'll doin tonight?" (integer) 0 redis 127.0.0.1:6379> PUBLISH myradioshow "Hello? Is anyone listening? I'm not wearing pants." (integer) 0 Notice there are no clients receiving the messages on your "myradioshow" channel (that's the 0 in the response). Nobody is listening. Now, open another redis-cli (or for more fun times have a friend open up their redis-cli and connect to your server) and SUBSCRIBE to the channel: redis 127.0.0.1:6379> SUBSCRIBE myradioshow Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "myradioshow" 3) (integer) 1 Go back to your original redis-cli and continue your show: redis 127.0.0.1:6379> PUBLISH myradioshow "Next caller gets a free loaf of bread!" (integer) 1 Notice that "1" at the end? You have a listener! Like magic, in your SUBSCRIBE-d terminal: 1) "message" 2) "myradioshow" 3) "Next caller gets a free loaf of bread!" Of course, in reality, you're probably going to want to do stuff that's more useful than telling your clients about your pants-less lifestyle, such as firing events on your server or running some kind of tasks/jobs. Maybe not though! :)
Redis
6,487,394
48
Is there a way I can flush my redis db using redis? I'm looking for something like redis.flushdb() or redis.flushall()
Redis-py actually has this functionality: import redis r = redis.Redis() r.flushdb()
Redis
45,916,183
47
I just built the redis docker instance $ docker pull redis After which I ran it like this. $ docker run --name=redis --detach=true --publish=6379:6379 redis I get the following $ docker ps key redis "/sbin/entrypoint.sh" 22 minutes ago Up 22 minutes 0.0.0.0:6379->6379/tcp redis To me the above means that it is now running listening on port 6379 on localhost or 127.0.0.1 or 0.0.0.0. But to my great surprise, when I try to connect is responds with connection refused. Please can someone throw some light.
You need to provide more information about your environment (OS, Docker installation, etc), but basically, if you start your Redis container like this: docker run --name=redis-devel --publish=6379:6379 --hostname=redis --restart=on-failure --detach redis:latest It should expose the port no matter what. The only reason you might not be able to connect to it, is if you've messed up your bridge interface, if you're on Linux, or you're using a docker machine with its own network interface and IP address and you're not connecting to that IP address. If you're using Docker for Mac, then that only supports routing to the localhost address, since bridging on Mac hosts doesn't work yet. Anyway, on MacOS with Docker for Mac (not the old Docker Toolbox), the following should be enough to get your started: ➜ ~ docker run --name=redis-devel --publish=6379:6379 --hostname=redis --restart=on-failure --detach redis:latest 6bfc6250cc505f82b56a405c44791f193ec5b53469f1625b289ef8a5d7d3b61e ➜ ~ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6bfc6250cc50 redis:latest "docker-entrypoint.s…" 10 minutes ago Up 10 minutes 0.0.0.0:6379->6379/tcp redis-devel ➜ ~ redis-cli ping PONG ➜ ~
Redis
33,675,914
47
I'm using redis lists and pushing to new items to a list. The problem is I really only need the most recent 10 items in a list. I'm using lpush to add items to a list and lrange to get the most recent 10. Is there anyway to drop items after a certain number? I'll end up with lists that may have 1,000's of items and can cause performance issues with latency. Thank you!
After every lpush, call ltrim to trim the list to 10 elements See http://redis.io/commands/ltrim
Redis
12,060,004
47
By "durable" I mean, the server can crash at any time, and as long as the disk remains in tact, no data is lost (see ACID). Seems like that's what journaling mode is for, but if you enable journaling, doesn't that defeat the purpose of operating on in-memory data? Read operations might not be affected by journaling, but it seems like journaling would kill your write performance.
Redis is not usually deployed as a "durable" datastore (in the sense of the "D" in ACID.), even with journaling. Most use cases intentionally sacrifice a little durability in return for speed. However, the "append only file" storage mode can optionally be configured to operate in a durable manner, at the cost of performance. It will have to pay for an fsync() on every modification. To configure this, set these two options in your .conf file: appendonly yes appendfsync always From the docs: How durable is the append only file? Check redis.conf, you can configure how many times Redis will fsync() data on disk. There are three options: Fsync() every time a new command is appended to the append log file. Very very slow, very safe. Fsync() one time every second. Fast enough, and you can lose 1 second of data if there is a disaster. Never fsync(), just put your data in the hands of the Operating System. The faster and unsafer method. (Note that the default for appendfsync in the configuration file shipping with Redis post-2.0.0 is everysec, and not always.)
Redis
2,449,969
47
I'm switching over from a heroku addon to a direct redis cloud account and am a bit puzzled on how to generate the redis url with the auth info. The old heroku add-on url was in the format of redis://rediscloud:mypassword@redis... However in the dashboard and documentation I don't see any mention of a username to go along with the password. Do I still set rediscloud as the username in my new account and connection string. Does it even matter what I set as the username there?
I use golang (https://github.com/garyburd/redigo) and connect to aliyun cloud Redis (link: https://www.aliyun.com/product/kvstore?spm=5176.8006303.267657.7.cW2xH) By the connect string: redis://arbitrary_usrname:password@ipaddress:6379/0 when 0 is the database index and success
Redis
44,344,628
46
I am trying to find out values stored in a list of keys which match a pattern from redis. I tried using SCAN so that later on i can use MGET to get all the values, The problem is: SCAN 0 MATCH "foo:bar:*" COUNT 1000 does not return any value whereas SCAN 0 MATCH "foo:bar:*" COUNT 10000 returns the desired keys. How do i force SCAN to look through all the existing keys? Do I have to look into lua for this?
With the code below you will scan the 1000 first object from cursor 0 SCAN 0 MATCH "foo:bar:*" COUNT 1000 In result, you will get a new cursor to recall SCAN YOUR_NEW_CURSOR MATCH "foo:bar:*" COUNT 1000 To scan 1000 next object. Then when you increase COUNT from 1000 to 10000 and retrieve data you scan more keys then in your case match more keys. To scan the entire list you need to recall SCAN until the cursor give in response return zero (i.e entire scan) Use INFO command to get your amount of keys like db0:keys=YOUR_AMOUNT_OF_KEYS,expires=0,avg_ttl=0 Then call SCAN 0 MATCH "foo:bar:*" COUNT YOUR_AMOUNT_OF_KEYS
Redis
33,166,812
46
I did an package manager update-package command to update our project to the latest binaries. I almost published it because it passed all the tests until luckily I had found a problem that needed some more debugging. My mouth fell open when I suddenly saw this exception message: The free-quota limit on '6000 Redis requests per hour' has been reached. Please see https://servicestack.net to upgrade to a commercial license. What if I published this site? Practices like these are simply revolting! There is no console warning or whatsoever about not having any license. It's like having an 'open source' trojan horse spread out into your projects. Are there any good alternatives to servicestack? EDIT: Reading all the comments I guess my first reaction was a bit strong. Nuget updated from v3 to v4 automatically and although I didn't notice any breaking changes, reading the release notes would have been the right thing to do instead of bashing an otherwise good product. That being said, I think people will burn their hands on this exception, since 6000 requests would be enough to come through the tests and publishing this is disastrous.
We are migrating to Booksleeve, which was developed by the people who have built StackOverflow itself. So far we had very good experiences. The money is not the issue (the cost of migration is higher than paying for the license), we're doing it because we just don't want to enter a business relationship with company with sketchy practices like this. (And no, we didn't accept any license or anything, all we did was a git pull from GitHub.)
Redis
20,785,419
45
I have JSON (<1k) to store in Redis through node.js. What are the pros and cons of storing it as an object or string? Are there other options I missed? All processing will ultimately happen on the client side, so converting into an object is not necessary. SET var images = JSON.parse(data); // data is already JSON, is this needed? callback(images); // sends result to the user r.set('images:' + req.query, images); // saving the object GET callback(images);
You can store JSON in redis either as a plain string in dedicated key (or member/value of a set/list) or in a hash structure. If you look at node_redis docs into Friendlier hash commands part you'll see that it gives you some useful methods for manipulating JSON based data. Pros of this approach is that it allows you to get/set only part of the original object and it might also consume less memory compared to plain strings.
Redis
8,986,982
45
I can't find anywhere online what is default TTL in Redis. I know that I can set TTL for specific SET, but don't know what is default TTL. Can someone tell me what default time to live is in Redis?
There is no default TTL. By default, keys are set to live forever.
Redis
49,133,314
44
I'm building an application with ExpressJS, Mongodb(Mogoose). Application contains routes where user has to be authenticated before accessing it. Currently I have written a express middleware to do the same. Here with the help of JWT token I'm making mongodb query to check whether user is authenticated or not. but feel this might put unnecessary request load on my database. should I integrate redis for this specific task? does it will improve API performance? or should go ahead with existing mongodb approach? would be helpful if I get more insights on this.
TLDR: If you want the capability to revoke a JWT at some point, you'll need to look it up. So yes, something fast like Redis can be useful for that. One of the well documented drawbacks of using JWTs is that there's no simple way to revoke a token if for example a user needs to be logged out or the token has been compromised. Revoking a token would mean to look it up in some storage and then deciding what to do next. Since one of the points of JWTs is to avoid round trips to the db, a good compromise would be to store them in something less taxing than an rdbms. That's a perfect job for Redis. Note however that having to look up tokens in storage for validity still reintroduces statefulness and negates some of the main benefits of JWTs. To mitigate this drawback make the list a blacklist (or blocklist, i.e. a list of invalid tokens). To validate a token, you look it up on the list and verify that it is not present. You can further improve on space and performance by staggering the lookup steps. For instance, you could have a tiny in-app storage that only tracks the first 2 or 3 bytes of your blacklisted tokens. Then the redis cache would track a slightly larger version of the same tokens (e.g. the first 4 or 5 bytes). You can then store a full version of the blacklisted tokens using a more persistent solution (filesystem, rdbms, etc). This is an optimistic lookup strategy that will quickly confirm that a token is valid (which would be the more common case). If a token happens to match an item in the in-app blacklist (because its first few bytes match), then move on to do an extra lookup on the redis store, then the persistent store if need be. Some (or all) of the stores may be implemented as tries or hash tables. Another efficient and relatively simple to implement data structure to consider is something called a Bloom filter. As your revoked tokens expire (of old age), a periodic routine can remove them from the stores. Keep your blacklist short and manageable by also shortening the lifespan of your tokens. Remember that JWTs shine in scenarios where revoking them is the exception. If you routinely blacklist millions of long-lasting tokens, it may indicate that you have a different problem.
Redis
44,890,564
44
I Installed Redis Server on ubuntu 16.04. but when I try to start the redis service using $ sudo systemctl start redis I receive message: Failed to start redis.service: Unit redis-server.service is masked. I don't have any idea about this error.
I found the solution. I think it will help for others | systemctl unmask servicename $ sudo systemctl unmask redis-server.service
Redis
40,317,106
44
The Setup: Imagine a 'twitter like' service where a user submits a post, which is then read by many (hundreds, thousands, or more) users. My question is regarding the best way to architect the cache & database to optimize for quick access & many reads, but still keep the historical data so that users may (if they want) see older posts. The assumption here is that 90% of users would only be interested in the new stuff, and that the old stuff will get accessed occasionally. The other assumption here is that we want to optimize for the 90%, and its ok if the older 10% take a little longer to retrieve. With this in mind, my research seems to strongly point in the direction of using a cache for the 90%, and then to also store the posts in another longer-term persistent system. So my idea thus far is to use Redis for the cache. The advantages is that Redis is very fast, and also it has built in pub/sub which would be perfect for publishing posts to many people. And then I was considering using MongoDB as a more permanent data store to store the same posts which will be accessed as they expire off of Redis. Questions: 1. Does this architecture hold water? Is there a better way to do this? 2. Regarding the mechanism for storing posts in both the Redis & MongoDB, I was thinking about having the app do 2 writes: 1st - write to Redis, it then is immediately available for the subscribers. 2nd - after successfully storing to Redis, write to MongoDB immediately. Is this the best way to do it? Should I instead have Redis push the expired posts to MongoDB itself? I thought about this, but I couldn't find much information on pushing to MongoDB from Redis directly.
It is actually sensible to associate Redis and MongoDB: they are good team players. You will find more information here: MongoDB with redis One critical point is the resiliency level you need. Both Redis and MongoDB can be configured to achieve an acceptable level of resiliency, and these considerations should be discussed at design time. Also, it may put constraint on the deployment options: if you want master/slave replication for both Redis and MongoDB you need at least 4 boxes (Redis and MongoDB should not be deployed on the same machine). Now, it may be a bit simpler to keep Redis for queuing, pub/sub, etc ... and store the user data in MongoDB only. Rationale is you do not have to design similar data access paths (the difficult part of this job) for two stores featuring different paradigms. Also, MongoDB has built-in horizontal scalability (replica sets, auto-sharding, etc ...) while Redis has only do-it-yourself scalability. Regarding the second question, writing to both stores would be the easiest way to do it. There is no built-in feature to replicate Redis activity to MongoDB. Designing a daemon listening to a Redis queue (where activity would be posted) and writing to MongoDB is not that hard though.
Redis
11,218,941
44
How do you use the node.js redis library, what are the core concepts of redis and what does all the redis functions do, e.g. hset, hget etc? Could I have some example.
How do you use the nodejs redis library Check out node_redis and its examples. what are the core concepts of redis You should look at redis data types in order to get a bigger picture of its concepts and data types. what does all the redis functions do Try to look at this introduction in order to better understand its commands.
Redis
5,656,991
44
After setting a DataFrame to redis, then getting it back, redis returns a string and I can't figure out a way to convert this str to a DataFrame. How can I do these two appropriately?
set: redisConn.set("key", df.to_msgpack(compress='zlib')) get: pd.read_msgpack(redisConn.get("key"))
Redis
37,943,778
43
How to completely disable RDB and AOF? I don't care about Persistence and want it to be in mem only. I have already commented out the: #save 900 1 #save 300 10 #save 60 10000 But this did not help and I see that Redis still tries to write to disk. I know that Redis wants to write to disk because I get this error: "Failed opening .rdb for saving: Permission denied" I don't care about the error, because I want to disable the Persistence altogether.
If you want to change the redis that is running, log into the redis, and disable the aof: config set appendonly no disable the rdb: config set save "" If you want to make these changes effective after restarting redis, using config rewrite to make these changes to redis conf file. If your redis have not started, just make some changes to redis.conf, appendonly no save "" make sure there are no sentences like "save 60 1000" after the upper sentences, since the latter would rewrite the former.
Redis
27,681,402
43
I am using Redis with StackExchange.Redis. I have multiple threads that will at some point access and edit the value of the same key, so I need to synchronize the manipulation of the data. Looking at the available functions, I see that there are two functions, TakeLock and ReleaseLock. However, these functions take both a key and a value parameter rather than the expected single key to be locked. The intellisene documentation and source on GitHub don't explain how to use the LockTake and LockRelease functions or what to pass in for the key and value parameters. Q: What is the correct usage of LockTake and LockRelease in StackExchange.Redis? Pseudocode example of what I'm aiming to do: //Add Items Before Parallel Execution redis.StringSet("myJSONKey", myJSON); //Parallel Execution Parallel.For(0, 100, i => { //Some work here //.... //Lock redis.LockTake("myJSONKey"); //Manipulate var myJSONObject = redis.StringGet("myJSONKey"); myJSONObject.Total++; Console.WriteLine(myJSONObject.Total); redis.StringSet("myJSONKey", myNewJSON); //Unlock redis.LockRelease("myJSONKey"); //More work here //... });
There are 3 parts to a lock: the key (the unique name of the lock in the database) the value (a caller-defined token which can be used both to indicate who "owns" the lock, and to check that releasing and extending the lock is being done correctly) the duration (a lock intentionally is a finite duration thing) If no other value comes to mind, a guid might make a suitable "value". We tend to use the machine-name (or a munged version of the machine name if multiple processes could be competing on the same machine). Also, note that taking a lock is speculative, not blocking. It is entirely possible that you fail to obtain the lock, and hence you may need to test for this and perhaps add some retry logic. A typical example might be: RedisValue token = Environment.MachineName; if(db.LockTake(key, token, duration)) { try { // you have the lock do work } finally { db.LockRelease(key, token); } } Note that if the work is lengthy (a loop, in particular), you may want to add some occasional LockExtend calls in the middle - again remembering to check for success (in case it timed out). Note also that all individual redis commands are atomic, so you don't need to worry about two discreet operations competing. For more complexing multi-operation units, transactions and scripting are options.
Redis
25,127,172
43
Could you please explain me following example from "The Little Redis Book": With the code above, we wouldn't be able to implement our own incr command since they are all executed together once exec is called. From code, we can't do: redis.multi() current = redis.get('powerlevel') redis.set('powerlevel', current + 1) redis.exec() That isn't how Redis transactions work. But, if we add a watch to powerlevel, we can do: redis.watch('powerlevel') current = redis.get('powerlevel') redis.multi() redis.set('powerlevel', current + 1) redis.exec() If another client changes the value of powerlevel after we've called watch on it, our transaction will fail. If no client changes the value, the set will work. We can execute this code in a loop until it works. Why we can't execute increment in transaction that can't be interrupted by other command? Why we need to iterate instead and wait until nobody changes value before transaction starts?
There are several questions here. 1) Why we can't execute increment in transaction that can't be interrupted by other command? Please note first that Redis "transactions" are completely different than what most people think transactions are in classical DBMS. # Does not work redis.multi() current = redis.get('powerlevel') redis.set('powerlevel', current + 1) redis.exec() You need to understand what is executed on server-side (in Redis), and what is executed on client-side (in your script). In the above code, the GET and SET commands will be executed on Redis side, but assignment to current and calculation of current + 1 are supposed to be executed on client side. To guarantee atomicity, a MULTI/EXEC block delays the execution of Redis commands until the exec. So the client will only pile up the GET and SET commands in memory, and execute them in one shot and atomically in the end. Of course, the attempt to assign current to the result of GET and incrementation will occur well before. Actually the redis.get method will only return the string "QUEUED" to signal the command is delayed, and the incrementation will not work. In MULTI/EXEC blocks you can only use commands whose parameters can be fully known before the begining of the block. You may want to read the documentation for more information. 2) Why we need to iterate instead and wait until nobody changes value before transaction starts? This is an example of concurrent optimistic pattern. If we used no WATCH/MULTI/EXEC, we would have a potential race condition: # Initial arbitrary value powerlevel = 10 session A: GET powerlevel -> 10 session B: GET powerlevel -> 10 session A: current = 10 + 1 session B: current = 10 + 1 session A: SET powerlevel 11 session B: SET powerlevel 11 # In the end we have 11 instead of 12 -> wrong Now let's add a WATCH/MULTI/EXEC block. With a WATCH clause, the commands between MULTI and EXEC are executed only if the value has not changed. # Initial arbitrary value powerlevel = 10 session A: WATCH powerlevel session B: WATCH powerlevel session A: GET powerlevel -> 10 session B: GET powerlevel -> 10 session A: current = 10 + 1 session B: current = 10 + 1 session A: MULTI session B: MULTI session A: SET powerlevel 11 -> QUEUED session B: SET powerlevel 11 -> QUEUED session A: EXEC -> success! powerlevel is now 11 session B: EXEC -> failure, because powerlevel has changed and was watched # In the end, we have 11, and session B knows it has to attempt the transaction again # Hopefully, it will work fine this time. So you do not have to iterate to wait until nobody changes the value, but rather to attempt the operation again and again until Redis is sure the values are consistent and signals it is successful. In most cases, if the "transactions" are fast enough and the probability to have contention is low, the updates are very efficient. Now, if there is contention, some extra operations will have to be done for some "transactions" (due to the iteration and retries). But the data will always be consistent and no locking is required.
Redis
10,750,626
43
I'm using Redis version 2.2.13 jack@ubuntu:~/redis$ src/redis-server [23900] 14 Sep 14:28:52 # Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf' [23900] 14 Sep 14:28:52 # Opening port: bind: Address already in use So I follow the above instructions and try redis-server $HOME/redis/redis.conf Which gives me the following error: *** FATAL CONFIG FILE ERROR *** Reading the configuration file, at line 135 >>> 'slave-serve-stale-data yes' Bad directive or wrong number of arguments The file has the following comments: # When a slave lost the connection with the master, or when the replication # is still in progress, the slave can act in two different ways: # # 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will # still reply to client requests, possibly with out of data data, or the # data set may just be empty if this is the first synchronization. # # 2) if slave-serve-stale data is set to 'no' the slave will reply with # an error "SYNC with master in progress" to all the kind of commands # but to INFO and SLAVEOF. How can I resolve this issue?
I had this same problem, but I forgot that redis persists. If you get this error, try this command: redis-cli ping if you get PONG as a response, then Redis is running, and the port is in use, by Redis.
Redis
7,417,232
43
I want an autocomplete feature. I have short descriptive strings on a property of a data type. I have a list of ids in redis for the datatype ordered by created date and I use the ids to set and get properties for the datatype as explained in the redis type documentation. I don't use hash tables. What's the best way to get a set of strings matching what's been typed into an autocomplete input box given this setup? Going through all ids and checking the property I want to search - for each keystroke seems like the wrong way to do this. EDIT: In addition to the answers below, I've been shown this: http://antirez.com/post/autocomplete-with-redis.html
You need to set up an index using sets or sorted sets that you write to when you save anything. There's a good writeup at http://web.archive.org/web/20121013063245/http://playnice.ly/blog/2010/05/05/a-fast-fuzzy-full-text-index-using-redis that is pretty close to what I use myself.
Redis
6,401,194
43
If a user is already logged in and tries to login again in a new instance I'd like it to log out the other user instance. I don't want the same user to be logged in twice on my application. Currently the session is stored in a Redis store, i'm using express / connect to handle the session storage. One of the functions available which could be used to destroy the session is as follows: .destroy(sid, callback) However I need to find that session id before I call .destroy(). In Redis the username is stored as a part of the session. Question: Is it possible to query Redis to obtain the session id based on the username?
req.sessionID will provide you the session's ID, where req is a request object.
Redis
9,291,548
42
I'm using Resque on a rails-3 project to handle jobs that are scheduled to run every 5 minutes. I recently did something that snowballed the creation of these jobs and the stack has hit over 1000 jobs. I fixed the issue that caused that many jobs to be queued and now the problem I have is that the jobs created by the bug are still there and therefore It becomes difficult to test something since a job is added to a queue with 1000+ jobs. I can't seem to stop these jobs. I have tried removing the queue from the redis-cli using the flushall command but it didn't work. Am I missing something? coz I can't seem to find a way of getting rid of these jobs.
Playing off of the above answers, if you need to clear all of your queues, you could use the following: Resque.queues.each{|q| Resque.redis.del "queue:#{q}" }
Redis
5,880,962
42
What are the strengths and weaknesses of the various NoSQL databases available? In particular, it seems like Redis is weak when it comes to distributing write load over multiple servers. Is that the case? Is it a big problem? How big does a service have to grow before that could be a significant problem?
The strengths and weaknesses of the NoSQL databases (and also SQL databases) is highly dependent on your use case. For very large projects, performance is king; but for brand new projects, or projects where time and money are limited, simplicity and time-to-market are probably the most important. For teaching yourself (broadening your perspective, becoming a better, more valuable programmer), perhaps the most important thing is simple, solid fundamental concepts. What kind of project do you have in mind? Some strengths and weaknesses, off the top of my head: Redis Very simple key-value "global variable server" Very simple (some would say "non-existent") query system Easily the fastest in this list Transactions Data set must fit in memory Immature clustering, with unclear future (I'm sure it'll be great, but it's not yet decided.) Cassandra Arguably the most community momentum of the BigTable-like databases Probably the easiest of this list to manage in big/growing clusters Support for map/reduce, good for analytics, data warehousing MUlti-datacenter replication Tunable consistency/availability No single point of failure You must know what queries you will run early in the project, to prepare the data shape and indexes CouchDB Hands-down the best sync (replication) support, supporting master/slave, master/master, and more exotic architectures HTTP protocol, browsers/apps can interact directly with the DB partially or entirely. (Sync is also done over HTTP) After a brief learning curve, pretty sophisticated query system using Javascript and map/reduce Clustered operation (no SPOF, tunable consistency/availability) is currently a significant fork (BigCouch). It will probably merge into Couch but there is no roadmap. Similarly, clustering and multi-datacenter are theoretically possible (the "exotic" thing I mentioned) however you must write all that tooling yourself at this time. Append only file format (both databases and indexes) consumes disk surprisingly quickly, and you must manually run compaction (vacuuming) which makes a full copy of all records in the database. The same is required for each index file. Again, you have to be your own toolsmith.
Redis
4,720,508
42
In Redis 4.0, there is a new command UNLINK to delete the keys in Redis memory. This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. This is where the command name comes from: the command just unlinks the keys from the keyspace. The actual removal will happen later asynchronously. So one can always (100% times) use UNLINK instead of DEL as UNLINK is nonblocking, unlike DEL, right?
Before discussing which one is better, let's take a look at the difference between these commands. Both DEL and UNLINK free the key part in blocking mode. And the difference is the way they free the value part. DEL always frees the value part in blocking mode. However, if the value is too large, e.g. too many allocations for a large LIST or HASH, it blocks Redis for a long time. In order to solve the problem, Redis implements the UNLINK command, i.e. an 'non-blocking' delete. In fact, UNLINK is NOT always non-blocking/async. If the value is small, e.g. the size of LIST or HASH is less than 64, the value will be freed immediately. In this way, UNLINK is almost the same as DEL, except that it costs a few more function calls than DEL. However, if the value is large, Redis puts the value into a list, and the value will be freed by another thread i.e. the non-blocking free. In this way, the main thread has to do some synchronization with the background thread, and that's also a cost. In a conclusion, if the value is small, DEL is at least, as good as UNLINK. If value is very large, e.g. LIST with thousands or millions of items, UNLINK is much better than DEL. You can always safely replace DEL with UNLINK. However, if you find the thread synchronization becomes a problem (multi-threading is always a headache), you can rollback to DEL. UPDATE: Since Redis 6.0, there's a new configuration: lazyfree-lazy-user-del. You can set it to be yes, and Redis will run the DEL command as if running a UNLINK command.
Redis
45,818,371
41
I have done simple performance test on my local machine, this is python script: import redis import sqlite3 import time data = {} N = 100000 for i in xrange(N): key = "key-"+str(i) value = "value-"+str(i) data[key] = value r = redis.Redis("localhost", db=1) s = sqlite3.connect("testDB") cs = s.cursor() try: cs.execute("CREATE TABLE testTable(key VARCHAR(256), value TEXT)") except Exception as excp: print str(excp) cs.execute("DROP TABLE testTable") cs.execute("CREATE TABLE testTable(key VARCHAR(256), value TEXT)") print "[---Testing SQLITE---]" sts = time.time() for key in data: cs.execute("INSERT INTO testTable VALUES(?,?)", (key, data[key])) #s.commit() s.commit() ste = time.time() print "[Total time of sql: %s]"%str(ste-sts) print "[---Testing REDIS---]" rts = time.time() r.flushdb()# for empty db for key in data: r.set(key, data[key]) rte = time.time() print "[Total time of redis: %s]"%str(rte-rts) I expected redis to perform faster, but the result shows that it much more slower: [---Testing SQLITE---] [Total time of sql: 0.615846157074] [---Testing REDIS---] [Total time of redis: 10.9668009281] So, the redis is memory based, what about sqlite? Why redis is so slow? When I need to use redis and when I need to use sqlite?
from the redis documentation Redis is a server: all commands involve network or IPC roundtrips. It is meaningless to compare it to embedded data stores such as SQLite, Berkeley DB, Tokyo/Kyoto Cabinet, etc ... because the cost of most operations is precisely dominated by network/protocol management. Which does make sense though it's an acknowledgement of speed issues in certain cases. Redis might perform a lot better than sqlite under multiples of parallel access for instance. The right tool for the right job, sometimes it'll be redis other times sqlite other times something totally different. If this speed test is a proper showing of what your app will realistically do then sqlite will serve you better and it's good that you did this benchmark.
Redis
11,216,647
41
The Redis service is available on my hosting, and if i connect it for money, it is available only for me, since Redis rises in a separate docker container. But, if i turn it off, then Redis can still be used for free, though server-wide. And here I am connecting to the server-wide Redis: $redis = new Redis (); $redis->connect('127.0.0.1', 6379); And I see there about 300,000 records of other people's sites. $allKeys = $redis->keys('*'); echo(count($allKeys)); // ~300000 echo ($allKeys[10000]); // some data of some site echo ($redis->get($allKeys[10000])); // some data of some site And i can change every record! Like this: $redis->set($allKeys[10000], 0); That is, someone uses the server-wide Redis and I believe that the user is not aware of the public availability of their data. He just turned on the "Use Redis" checkbox somewhere in WordPress. And the question is: is the hosting provider responsible for this? After all, an ordinary user believes that his data is stored only on his server and is available only to him. The technical support response was: everything is ok. But I don’t think so, so I ask.
This hosting provider is responsible for the security breach. Considering OWASP's top ten Web application security risks, this is an issue of few security risks: Broken Authentication, Sensitive Data Exposure, and Broken Access Control. What is your next step is up to you. You should inform the hosting provider, users should be informed by the hosting provider for the possible data breach. This is a very serious security and legal matter since someone's possibly private data is accessible to other users. See: https://owasp.org/www-project-top-ten/
Redis
60,477,527
40
Can anyone help me install php-redis in MAC OSX . brew install php-redis not working. pecl install php-redis also not working getting - invalid package name/package file "php-redis". Homebrew Error: homebrew_error
git clone https://www.github.com/phpredis/phpredis.git cd phpredis phpize && ./configure && make && sudo make install Add extension=redis.so in your php.ini brew services restart [email protected] make test You can check working or not php -r "if (new Redis() == true){ echo \"\r\n OK \r\n\"; }"
Redis
51,908,004
40
When calling Lua scripts from within Redis, it is possible to pass values in two arrays: KEYS and ARGV. What is the difference? How does Redis treat values in the KEYS array? What if, in my script, I have to use keys dynamically generated at run time?
All your questions are answered at the EVAL page, but since you asked...: What is the difference? KEYS is used to pass key names whereas ARGS should be for anything else. This isn't exactly enforced (i.e. most times you'd be ok mixing them) but could lead to potential problems if not followed. How does Redis treat values in the KEYS array? The contents of KEYS are checked to verify that all keys are available to the Redis shard that's running the script. This mechanism is in place to allow running scripts in a Redis cluster deployment. What if, in my script, I have to use keys dynamically generated at run time? See previous answers - that's doable but you'd going against the recommendations. Your script will be safe to run only on a stand alone Redis instance and since this behavior isn't specified, it may break in future releases.
Redis
32,089,406
40
I have installed redis using sudo apt-get install redis-server command but I am receiving this error when I run my Python program: ImportError: No module named redis Any idea what's going wrong or if I should install any other package as well? I am using Ubuntu 13.04 and I have Python 2.7.
To install redis-py, simply: $ sudo pip install redis or alternatively (you really should be using pip though): $ sudo easy_install redis or from source: $ sudo python setup.py install Getting Started >>> import redis >>> r = redis.StrictRedis(host='localhost', port=6379, db=0) >>> r.set('foo', 'bar') True >>> r.get('foo') 'bar' Details:https://pypi.python.org/pypi/redis
Redis
19,288,900
40
Question 1: I know Redis load all the data into memory, thus improving the read/write speed. So, does it mean that if my memory size is 2G, the maximum dataset size should not be larger than 2G? Now my database has a 100G+ data, the memory of my server cannot be larger than 32G, so, Redis is no longer suitable for me? Question 2: Is Redis a distributed system or not? When I use google to search for redis's CAP property, it says Redis is not a distributed system, so, it has nothing to do with CAP . But from Wikipedia, it says it has a master-slave architecture, one master with many slaves. How confusing.
Regarding question 1, Redis is an in-memory store with some persistency capabilities. All your dataset should fit in memory. A single instance is therefore limited by the maximum memory of your server. Now, you can also shard the data to several Redis instances, running on multiple servers. Provided you have the budget for it, it is perfectly possible to store 100GB - 1TB of data on a set of Redis boxes. Please note sharding is not automatic: it has to be implemented by the client or the application. It also puts some constraints on the operations you can do on your data (for instance it would not be possible on server-side to calculate the intersections of two sets hosted by different Redis instances). Regarding question 2, a single Redis instance is not a distributed system. It is a remote centralized store. Now by using several Redis instances, you can build a distributed system. Because it is a do-it-yourself approach, you can decide to make it a CP or AP system. A single instance can replicate its activity to slave instances (which are therefore eventually consistent with the master). The application can choose to always connect to the master for read and write. In that case, you may get a CP system. It can also write on the master, and read from all instances (including slaves), so you may get an AP system. I said "may", because it requires some significant work to build such systems on top of Redis. You can mix sharding and master/slave replication to build the distributed system you need. However, Redis only provides basic bricks to do this. Especially, it does offer very little to deal with resiliency and HA (and address the P in the CAP theorem). IMO, Redis sentinel alone is not enough to support an HA Redis configuration, since it only covers role management. You need to complement it with a resource manager, and put a lot of logic into the client/application. There is an on-going project called Redis Cluster, whose purpose is to provide a minimalistic ready-to-use distributed system, but it still lacks of lot of things, and is not usable yet for production purpose. If you need an off-the-shelf distributed store, Redis is probably not a good option. You will be better served by Cassandra, Riak, MongoDB, Couchbase, Aerospike, MySQL Cluster, Oracle NoSQL, etc ... However, if you want to build your own specialized system, Redis is an excellent component to build upon.
Redis
18,376,665
40
My team has decided to work with Redis via the ServiceStack.net Redis Client as an underlying repository for a new high-volume website we're working on. I'm not really sure where to look for documentation for this question (either for general Redis docs or specific ServiceStack.Net docs or both) - is there actually a definitive source for documentation on how to implement a Redis via ServiceStack.Net that includes all you need to know about both Redis concepts and ServiceStack.Net concepts, or do we need to integrate documentation from both aspects separately to get the full picture?. I'm just grappling with how exactly to store related objects in our model's object graph. Here's a simple scenario that I want to work with: There are two objects in the system: User and Feed. In RDBMS terms these two objects have a one-to-many relationship, that is, a User has a collection of Feed objects and a feed can only belong to one User. Feeds will always be accessed from Redis via their user but occasionally we'll want to get access to the user via a feed instance. So the question I have is whether we should be storing the related objects as properties or should we store the Id values of the related objects? To illustrate: Approach A: public class User { public User() { Feeds = new List<Feed>(); } public int Id { get; set; } public List<Feed> Feeds { get; set; } // Other properties } public class Feed { public long Id { get; set; } public User User { get; set; } } Approach B: public class User { public User() { FeedIds = new List<long>(); } public long Id { get; set; } public List<long> FeedIds { get; set; } public List<Feed> GetFeeds() { return repository.GetFeeds( FeedIds ); } } public class Feed { public long Id { get; set; } public long UserId { get; set; } public User GetUser() { return repository.GetUser( UserId ); } } Which of the above approaches will work best? I've seen both approaches used in various examples but I get the impression that some of the examples I've seen may not be best-practice. A few simple related questions: If I make a change to an object will it automatically be reflected in Redis or will it require a save? I'm assuming the latter, but need to be absolutely clear. If I (can) use Approach A, will an update to User object X be reflected throughout the entire object graph wherever it is referenced or will it be necessary to save changes across the graph? Is there a problem with storing an object via it's interface (i.e. use IList<Feed> as opposed to List<Feed>? Sorry if these questions are a little basic - until 2 weeks ago I'd never even heard of Redis - let alone ServiceStack - (nor had anyone in my team) so we're really starting from scratch here...
Rather than re-hash a lot of other documentation that's out there in the wild, I'll list a couple around for some background info around Redis + ServiceStack's Redis Client: What to think about when designing a NoSQL Redis application Designing a NoSQL Database using Redis General Overview of Redis and .NET Schemaless versioning and Data Migrations with C# Redis Client There is no magic - Redis is a blank canvas First I want to point out that using Redis as a data store just provides a blank canvas and doesn't have any concept of related entities by itself. i.e. it just provides access to distributed comp-sci data structures. How relationships get stored is ultimately up to the client driver (i.e. ServiceStack C# Redis Client) or the app developer, by using Redis's primitive data structure operations. Since all the major data structures are implemented in Redis, you basically have complete freedom on how you want to structure and store your data. Think how you would structure relationships in code So the best way to think about how to store stuff in Redis, is to completely disregard about how data is stored in an RDBMS table and think about how it is stored in your code, i.e. using the built-in C# collection classes in memory - which Redis mirrors in behavior with their server-side data-structures. Despite not having a concept of related entities, Redis's built-in Set and SortedSet data structures provide the ideal way to store indexes. E.g. Redis's Set collection only stores a max of 1 occurrence of an element. This means you can safely add items/keys/ids to it and not care if the item exists already as the end result will be the same had you called it 1 or 100 times - i.e. it's idempotent, and ultimately only 1 element remains stored in the Set. So a common use-case is when storing an object graph (aggregate root) is to store the Child Entity Ids (aka Foreign Keys) into a Set every time you save the model. Visualizing your data For a good visualization of how Entities are stored in Redis I recommend installing the Redis Admin UI which works well with ServiceStack's C# Redis Client as it uses the key naming convention below to provide a nice hierarchical view, grouping your typed entities together (despite all keys existing in the same global keyspace). To view and edit an Entity, click on the Edit link to see and modify the selected entity's internal JSON representation. Hopefully you'll be able to make better decisions about how to design your models once you can see how they're stored. How POCO / Entities are stored The C# Redis Client works with any POCOs that have a single primary key - which by default is expected to be Id (though this convention overridable with ModelConfig). Essentially POCOs gets stored into Redis as serialized JSON with both the typeof(Poco).Name and the Id used to form a unique key for that instance. E.g: urn:Poco:{Id} => '{"Id":1,"Foo":"Bar"}' POCOs in the C# Client are conventionally serialized using ServiceStack's fast Json Serializer where only properties with public getters are serialized (and public setters to get de-serialized back). Defaults are overrideable with [DataMember] attrs but not recommended since it uglifies your POCOs. Entities are blobbed So knowing that POCOs in Redis are just blobbed, you only want to keep non-aggregate root data on your POCOs as public properties (unless you purposely want to store redundant data). A good convention is to use methods to fetch the related data (since it wont get serialized) but also tells your app which methods make remote calls to read data. So the question on whether the Feed should get stored with the User is whether or not it's non-aggregate root data, i.e. whether or not you want to access the users feeds outside the context of the user? If no, then leave the List<Feed> Feeds property on the User type. Maintaining Custom Indexes If however you would like to keep all feeds accessible independently, i.e. with redisFeeds.GetById(1) then you will want to store it outside of the user and maintain an index linking the 2 entities. As you've noticed there are many ways to store relationships between entities and how you do so is largely a matter of preference. For the child entity in a parent>child relationship you would always want to store the ParentId with the child entity. For the Parent you can either choose to store a collection of ChildIds with the model and then do a single fetch for all child entities to re-hydrate the model. Another way is to maintain the index outside of the parent dto in its own Set for each parent instance. Some good examples of this is in the C# Source code of the Redis StackOverflow demo where the relationship of Users > Questions and Users > Answers is stored in: idx:user>q:{UserId} => [{QuestionId1},{QuestionId2},etc] idx:user>a:{UserId} => [{AnswerId1},{AnswerId2},etc] Although the C# RedisClient does include support for a default Parent/Child convention via its TParent.StoreRelatedEntities(), TParent.GetRelatedEntities<TChild>() and TParent.DeleteRelatedEntities() APIs where an index is maintained behind the scene that looks like: ref:Question/Answer:{QuestionId} => [{answerIds},..] Effectively these are just some of your possible options, where there are many different ways to achieve the same end and in which you also have the freedom to roll your own. NoSQL's schema-less, loose-typing freedoms should be embraced and you shouldn't be worried about trying to follow a rigid, pre-defined structure you might be familiar with when using an RDBMS. In conclusion, there's no real right way to store data in Redis, e.g. The C# Redis Client makes some assumptions in order to provide a high-level API around POCOs and it blobs the POCOs in Redis's binary-safe string values - though there are other clients will prefer to store an entities properties in Redis Hashes (Dictionaries) instead. Both will work.
Redis
8,914,349
40
Here is my code using socket.io as WebSocket and backend with pub/sub redis. var io = io.listen(server), buffer = []; var redis = require("redis"); var subscribe = redis.createClient(); **<--- open new connection overhead** io.on('connection', function(client) { console.log(client.request.headers.cookie); subscribe.get("..", function (err, replies) { }); subscribe.on("message",function(channel,message) { var msg = { message: [client.sessionId, message] }; buffer.push(msg); if (buffer.length > 15) buffer.shift(); client.send(msg); }); client.on('message', function(message){ }); client.on('disconnect', function(){ subscribe.quit(); }); }); Every new io request will create new redis connection. If someone open browser with 100 tabs then the redis client will open 100 connections. It doesn't look nice. Is it possible to reuse redis connection if the cookies are same? So if someone open many browser tabs also treat as open 1 connection.
Actually you are only creating a new redis client for every connection if you are instantiating the client on the "connection" event. What I prefer to do when creating a chat system is to create three redis clients. One for publishing, subscribing, and one for storing values into redis. for example: var socketio = require("socket.io") var redis = require("redis") // redis clients var store = redis.createClient() var pub = redis.createClient() var sub = redis.createClient() // ... application paths go here var socket = socketio.listen(app) sub.subscribe("chat") socket.on("connection", function(client){ client.send("welcome!") client.on("message", function(text){ store.incr("messageNextId", function(e, id){ store.hmset("messages:" + id, { uid: client.sessionId, text: text }, function(e, r){ pub.publish("chat", "messages:" + id) }) }) }) client.on("disconnect", function(){ client.broadcast(client.sessionId + " disconnected") }) sub.on("message", function(pattern, key){ store.hgetall(key, function(e, obj){ client.send(obj.uid + ": " + obj.text) }) }) })
Redis
5,739,357
40
How does one upgrade to a newer version of Redis with zero downtime? Redis slaves are read-only, so it seems like you'd have to take down the master and your site would be read-only for 45 seconds or more while you waited for it to reload the DB. Is there a way around this?
Redis Team has very good documentation on this Core Steps: Setup your new Redis instance as a slave for your current Redis instance. In order to do so you need a different server, or a server that has enough RAM to keep two instances of Redis running at the same time. If you use a single server, make sure that the slave is started in a different port than the master instance, otherwise the slave will not be able to start at all. Wait for the replication initial synchronization to complete (check the slave log file). Make sure using INFO that there are the same number of keys in the master and in the slave. Check with redis-cli that the slave is working as you wish and is replying to your commands. Configure all your clients in order to use the new instance (that is, the slave). Once you are sure that the master is no longer receiving any query (you can check this with the MONITOR command), elect the slave to master using the SLAVEOF NO ONE command, and shut down your master. Full Documentation: Upgrading or restarting a Redis instance without downtime
Redis
4,719,346
40
The queue:listen was not run on a server, so some jobs were pushed (using Redis driver) but never run. How could I count (or get all) these jobs? I did not find any artisan command to get this information.
Since Laravel 5.3 you can simply use Queue::size() (see PR).
Redis
35,412,779
39
I run my Integration Test cases with Spring Boot with the help of my local Redis server on my machine. But I want an embedded Redis server which is not dependent on any server and can run on any environment, like the H2 in-memory database. How can I do it? @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @IntegrationTest("server.port:0") @SpringApplicationConfiguration(classes = Application.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class MasterIntegrationTest { }
You can use an embedded Redis like https://github.com/kstyrc/embedded-redis Add the dependency to your pom.xml Adjust the properties for your integration test to point to your embedded redis, for example : spring: redis: host: localhost port: 6379 Instanciate the embedded redis server in a component that is defined in your tests only : @Component public class EmbededRedis { @Value("${spring.redis.port}") private int redisPort; private RedisServer redisServer; @PostConstruct public void startRedis() throws IOException { redisServer = new RedisServer(redisPort); redisServer.start(); } @PreDestroy public void stopRedis() { redisServer.stop(); } }
Redis
32,524,194
39
While I was following Azure documentation for how to use Redis Cache in Azure Portal I noticed this note: If you prefer to use a strong-named version of the StackExchange.Redis client library, choose StackExchange.Redis.StrongName; otherwise choose StackExchange.Redis. What is the strong-named ? and what is the proc and cons ? How to decide if I need it or not in my application ?
Do you need a strongly named Redis library? In all likelihood, especially if you never even encountered this term, the answer is no. But read on. What is strongly named? it's a .NET specific thing you can choose to sign your assembly with a cryptographic key this makes it possible to verify that you are actually loading/running something you expect to load/run the "strong name" includes the cryptographic signature together with the the usual name, version and things like that. Do you ever need strong names? probably not unless you have specific reasons. Some of these may be: historic (we used to sign our assemblies and why change now) corporate policies special circumstances such as something else you are using requires strong names (it used to be a requirement to have strong name if you wanted to add something to the GAC) possibly security considerations Is it a good idea to sign your assemblies? there are a lot of divided opinions very often strong names are a pain in so many ways with questionable benefits it has been a trend lately to not use strong names unless you really must Do you need a strongly named Redis library? unless you decide or have to sign your own application which uses Redis library you don't the strong names version of Redis library is identical to the other one it exists solely for the reason to make lives of those who need to use strong names easier
Redis
28,584,950
39
I'm using Celery (3.0.15) with Redis as a broker. Is there a straightforward way to query the number of tasks with a given name that exist in a Celery queue? And, as a followup, is there a way to cancel all tasks with a given name that exist in a Celery queue? I've been through the Monitoring and Management Guide and don't see a solution there.
# Retrieve tasks # Reference: http://docs.celeryproject.org/en/latest/reference/celery.events.state.html query = celery.events.state.tasks_by_type(your_task_name) # Kill tasks # Reference: http://docs.celeryproject.org/en/latest/userguide/workers.html#revoking-tasks for uuid, task in query: celery.control.revoke(uuid, terminate=True)
Redis
15,575,826
39
Pretty simple question. I am building a realtime game using nodejs as my backend and I am wondering if there is any information available on which one is more reliable and which one is more efficient? I am heavily using both Redis and Socket.io throughout my code. So I want to know whether I should be utilizing Socket.io's Rooms or I would be better off using redis' pub-sub ? Update: Just realized there is a very important reason why you may want to use redis pub/sub over socket.io rooms. With Socket.io rooms when you publish to listeners, the (browser)clients recieve the message, with redis it is actually the (redis~on server)clients who recieve messages. For this reason, if you want to inform all (server)clients of information specific to each client and maybe do some processing before passing on to browser clients, you are better off using redis. Using redis you can just fire off an event to generate each users individual data, where as with socket.io you have to actually generate all the users unique data at once, then loop through them and send them their individual data, which almost defeats the purpose of rooms, at least for me. Unfortunately for my purposes I am stuck with redis for now. Update 2: Ended up developing a plugin to use only 2 redis connections but still allow for individual client processing, see answer below....
Redis pub/sub is great in case all clients have direct access to redis. If you have multiple node servers, one can push a message to the others. But if you also have clients in the browser, you need something else to push data from a server to a client, and in this case, socket.io is great. Now, if you use socket.io with the Redis store, socket.io will use Redis pub/sub under the hood to propagate messages between servers, and servers will propagate messages to clients. So using socket.io rooms with socket.io configured with the Redis store is probably the simplest for you.
Redis
14,929,700
39
I know if I do redis-cli -h {ip_address} -p {port} I can connect to a specific port/ip but I've set my instance to not listen to any tcp/ip ports instead it listens to local socket. How can I establish a socket connection with the redis client?
You can connect from redis-cli or redis-benchmark simply by using the -s option and providing the path of your unix domain socket. For instance: redis-cli -s /tmp/redis.sock redis-benchmark -q -n 10000 -s /tmp/redis.sock
Redis
9,445,024
39
The GitHub guys recently released their background processing app which uses Redis: http://github.com/defunkt/resque http://github.com/blog/542-introducing-resque I have it working locally, but I'm struggling to get it working in production. Has anyone got a: Capistrano recipe to deploy workers (control number of workers, restarting them, etc) Deployed workers to separate machine(s) from where the main app is running, what settings were needed here? gotten redis to survive a reboot on the server (I tried putting it in cron but no luck) how did you work resque-web (their excellent monitoring app) into your deploy? Thanks! P.S. I posted an issue on Github about this but no response yet. Hoping some SO gurus can help on this one as I'm not very experienced in deployments. Thank you!
I'm a little late to the party, but thought I'd post what worked for me. Essentially, I have god setup to monitor redis and resque. If they aren't running anymore, god starts them back up. Then, I have a rake task that gets run after a capistrano deploy that quits my resque workers. Once the workers are quit, god will start new workers up so that they're running the latest codebase. Here is my full writeup of how I use resque in production: http://thomasmango.com/2010/05/27/resque-in-production
Redis
1,732,415
39
I am a little bit lost. I am reading Microsoft documentation for ASP.NET Core caching using Redis. And the documentation suggests to use Microsoft.Extensions.Caching.StackExchangeRedis which is an open source third party library. But I've seen some other tutorials are using Microsoft.Extensions.Caching.Redis, which is a more native asp.net core. And at the end they both use the same interface IDistributedCache. Why do I need Microsoft.Extensions.Caching.StackExchangeRedis? What advantages it has over Microsoft.Extensions.Caching.Redis?
A look at the dependency graph for Microsoft.Extensions.Caching.Redis and Microsoft.Extensions.Caching.StackExchangeRedis reveals it. Microsoft.Extensions.Caching.Redis is based on StackExchange redis 1.x library, whereas Microsoft.Extensions.Caching.StackExchangeRedis is based on 2.x of the same library. Also Microsoft.Extensions.Caching.Redis doesn't seem to target the 3.1 extension libraries (Microsoft.Extensions.Options/Caching.Abstractions) where the other does. So for .NET Core 3.x and newer use Microsoft.Extensions.Caching.StackExchangeRedis as the previous one may not be maintained as long as the new one.
Redis
59,847,571
38
I've been asked to evaluate RabbitMQ instead of Kafka but found it hard to find a situation where a message queue is more suitable than Kafka. Does anyone know use cases where a message queue fits better in terms of throughput, durability, latency, or ease-of-use?
RabbitMQ is a solid, general-purpose message broker that supports several protocols such as AMQP, MQTT, STOMP, etc. It can handle high throughput. A common use case for RabbitMQ is to handle background jobs or long-running task, such as file scanning, image scaling or PDF conversion. RabbitMQ is also used between microservices, where it serves as a means of communicating between applications, avoiding bottlenecks passing messages. Kafka is a message bus optimized for high-throughput ingestion data streams and replay. Use Kafka when you have the need to move a large amount of data, process data in real-time or analyze data over a time period. In other words, where data need to be collected, stored, and handled. An example is when you want to track user activity on a webshop and generate suggested items to buy. Another example is data analysis for tracking, ingestion, logging or security. Kafka can be seen as a durable message broker where applications can process and re-process streamed data on disk. Kafka has a very simple routing approach. RabbitMQ has better options if you need to route your messages in complex ways to your consumers. Use Kafka if you need to support batch consumers that could be offline or consumers that want messages at low latency.  In order to understand how to read data from Kafka, we first need to understand its consumers and consumer groups. Partitions allow you to parallelize a topic by splitting the data across multiple nodes. Each record in a partition is assigned and identified by its unique offset. This offset points to the record in a partition. In the latest version of Kafka, Kafka maintains a numerical offset for each record in a partition. A consumer in Kafka can either automatically commit offsets periodically, or it can choose to control this committed position manually. RabbitMQ will keep all states about consumed/acknowledged/unacknowledged messages. I find Kafka more complex to understand than the case of RabbitMQ, where the message is simply removed from the queue once it's acked. RabbitMQ's queues are fastest when they're empty, while Kafka retains large amounts of data with very little overhead - Kafka is designed for holding and distributing large volumes of messages. (If you plan to have very long queues in RabbitMQ you could have a look at lazy queues.) Kafka is built from the ground up with horizontal scaling (scale by adding more machines) in mind, while RabbitMQ is mostly designed for vertical scaling (scale by adding more power). RabbitMQ has a built-in user-friendly interface that lets you monitor and handle your RabbitMQ server from a web browser. Among other things, queues, connections, channels, exchanges, users and user permissions can be handled - created, deleted and listed in the browser and you can monitor message rates and send/receive messages manually. Kafka has a number of open-source tools, and also some commercial ones, offering the administration and monitoring functionalities. I would say that it's easier/gets faster to get a good understanding of RabbitMQ. In general, if you want a simple/traditional pub-sub message broker, the obvious choice is RabbitMQ, as it will most probably scale more than you will ever need it to scale. I would have chosen RabbitMQ if my requirements were simple enough to deal with system communication through channels/queues, and where retention and streaming is not a requirement. There are two main situations where I would choose RabbitMQ; For long-running tasks, when I need to run reliable background jobs. And for communication and integration within, and between applications, i.e as middleman between microservices; where a system simply needs to notify another part of the system to start to work on a task, like ordering handling in a webshop (order placed, update order status, send order, payment, etc.). In general, if you want a framework for storing, reading (re-reading), and analyzing streaming data, use Apache Kafka. It’s ideal for systems that are audited or those that need to store messages permanently. These can also be broken down into two main use cases for analyzing data (tracking, ingestion, logging, security etc.) or real-time processing. More reading, use cases and some comparison data can be found here: https://www.cloudamqp.com/blog/2019-12-12-when-to-use-rabbitmq-or-apache-kafka.html Also recommending the industry paper: "Kafka versus RabbitMQ: A comparative study of two industry reference publish/subscribe implementations": http://dl.acm.org/citation.cfm?id=3093908 I do work at a company providing both Apache Kafka and RabbitMQ as a Service.
RabbitMQ
42,151,544
546
I am new to message brokers like RabbitMQ which we can use to create tasks / message queues for a scheduling system like Celery. Now, here is the question: I can create a table in PostgreSQL which can be appended with new tasks and consumed by the consumer program like Celery. Why on earth would I want to setup a whole new tech for this like RabbitMQ? Now, I believe scaling cannot be the answer since our database like PostgreSQL can work in a distributed environment. I googled for what problems does the database poses for the particular problem, and I found: polling keeps the database busy and low performing locking of the table -> again low performing millions of rows of tasks -> again, polling is low performing Now, how does RabbitMQ or any other message broker like that solves these problems? Also, I found out that AMQP protocol is what it follows. What's great in that? Can Redis also be used as a message broker? I find it more analogous to Memcached than RabbitMQ. Please shed some light on this!
Rabbit's queues reside in memory and will therefore be much faster than implementing this in a database. A (good)dedicated message queue should also provide essential queuing related features such as throttling/flow control, and the ability to choose different routing algorithms, to name a couple(rabbit provides these and more). Depending on the size of your project, you may also want the message passing component separate from your database, so that if one component experiences heavy load, it need not hinder the other's operation. As for the problems you mentioned: polling keeping the database busy and low performing: Using Rabbitmq, producers can push updates to consumers which is far more performant than polling. Data is simply sent to the consumer when it needs to be, eliminating the need for wasteful checks. locking of the table -> again low performing: There is no table to lock :P millions of rows of task -> again polling is low performing: As mentioned above, Rabbitmq will operate faster as it resides RAM, and provides flow control. If needed, it can also use the disk to temporarily store messages if it runs out of RAM. After 2.0, Rabbit has significantly improved on its RAM usage. Clustering options are also available. In regards to AMQP, I would say a really cool feature is the "exchange", and the ability for it to route to other exchanges. This gives you more flexibility and enables you to create a wide array of elaborate routing typologies which can come in very handy when scaling. For a good example, see: (source: springsource.com) and: http://blog.springsource.org/2011/04/01/routing-topologies-for-performance-and-scalability-with-rabbitmq/ Finally, in regards to Redis, yes, it can be used as a message broker, and can do well. However, Rabbitmq has more message queuing features than Redis, as rabbitmq was built from the ground up to be a full-featured enterprise-level dedicated message queue. Redis on the other hand was primarily created to be an in-memory key-value store(though it does much more than that now; its even referred to as a swiss army knife). Still, I've read/heard many people achieving good results with Redis for smaller sized projects, but haven't heard much about it in larger applications. Here is an example of Redis being used in a long-polling chat implementation: http://eflorenzano.com/blog/2011/02/16/technology-behind-convore/
RabbitMQ
13,005,410
268
How can I delete all pending tasks without knowing the task_id for each task?
From the docs: $ celery -A proj purge or from proj.celery import app app.control.purge() (EDIT: Updated with current method.)
RabbitMQ
7,149,074
249
I am just starting to use RabbitMQ and AMQP in general. I have a queue of messages I have multiple consumers, which I would like to do different things with the same message. Most of the RabbitMQ documentation seems to be focused on round-robin, ie where a single message is consumed by a single consumer, with the load being spread between each consumer. This is indeed the behavior I witness. An example: the producer has a single queue, and send messages every 2 sec: var amqp = require('amqp'); var connection = amqp.createConnection({ host: "localhost", port: 5672 }); var count = 1; connection.on('ready', function () { var sendMessage = function(connection, queue_name, payload) { var encoded_payload = JSON.stringify(payload); connection.publish(queue_name, encoded_payload); } setInterval( function() { var test_message = 'TEST '+count sendMessage(connection, "my_queue_name", test_message) count += 1; }, 2000) }) And here's a consumer: var amqp = require('amqp'); var connection = amqp.createConnection({ host: "localhost", port: 5672 }); connection.on('ready', function () { connection.queue("my_queue_name", function(queue){ queue.bind('#'); queue.subscribe(function (message) { var encoded_payload = unescape(message.data) var payload = JSON.parse(encoded_payload) console.log('Recieved a message:') console.log(payload) }) }) }) If I start the consumer twice, I can see that each consumer is consuming alternate messages in round-robin behavior. Eg, I'll see messages 1, 3, 5 in one terminal, 2, 4, 6 in the other. My question is: Can I have each consumer receive the same messages? Ie, both consumers get message 1, 2, 3, 4, 5, 6? What is this called in AMQP/RabbitMQ speak? How is it normally configured? Is this commonly done? Should I just have the exchange route the message into two separate queues, with a single consumer, instead?
Can I have each consumer receive the same messages? Ie, both consumers get message 1, 2, 3, 4, 5, 6? What is this called in AMQP/RabbitMQ speak? How is it normally configured? No, not if the consumers are on the same queue. From RabbitMQ's AMQP Concepts guide: it is important to understand that, in AMQP 0-9-1, messages are load balanced between consumers. This seems to imply that round-robin behavior within a queue is a given, and not configurable. Ie, separate queues are required in order to have the same message ID be handled by multiple consumers. Is this commonly done? Should I just have the exchange route the message into two separate queues, with a single consumer, instead? No it's not, single queue/multiple consumers with each consumer handling the same message ID isn't possible. Having the exchange route the message onto into two separate queues is indeed better. As I don't require too complex routing, a fanout exchange will handle this nicely. I didn't focus too much on Exchanges earlier as node-amqp has the concept of a 'default exchange' allowing you to publish messages to a connection directly, however most AMQP messages are published to a specific exchange. Here's my fanout exchange, both sending and receiving: var amqp = require('amqp'); var connection = amqp.createConnection({ host: "localhost", port: 5672 }); var count = 1; connection.on('ready', function () { connection.exchange("my_exchange", options={type:'fanout'}, function(exchange) { var sendMessage = function(exchange, payload) { console.log('about to publish') var encoded_payload = JSON.stringify(payload); exchange.publish('', encoded_payload, {}) } // Recieve messages connection.queue("my_queue_name", function(queue){ console.log('Created queue') queue.bind(exchange, ''); queue.subscribe(function (message) { console.log('subscribed to queue') var encoded_payload = unescape(message.data) var payload = JSON.parse(encoded_payload) console.log('Recieved a message:') console.log(payload) }) }) setInterval( function() { var test_message = 'TEST '+count sendMessage(exchange, test_message) count += 1; }, 2000) }) })
RabbitMQ
10,620,976
240
The RabbitMQ Java client has the following concepts: Connection - a connection to a RabbitMQ server instance Channel - ??? Consumer thread pool - a pool of threads that consume messages off the RabbitMQ server queues Queue - a structure that holds messages in FIFO order I'm trying to understand the relationship, and more importantly, the associations between them. I'm still not quite sure what a Channel is, other than the fact that this is the structure that you publish and consume from, and that it is created from an open connection. If someone could explain to me what the "Channel" represents, it might help clear a few things up. What is the relationship between Channel and Queue? Can the same Channel be used to communicate to multiples Queues, or does it have to be 1:1? What is the relationship between Queue and the Consumer Pool? Can multiple Consumers be subscribed to the same Queue? Can multiple Queues be consumed by the same Consumer? Or is the relationship 1:1?
A Connection represents a real TCP connection to the message broker, whereas a Channel is a virtual connection (AMQP connection) inside it. This way you can use as many (virtual) connections as you want inside your application without overloading the broker with TCP connections. You can use one Channel for everything. However, if you have multiple threads, it's suggested to use a different Channel for each thread. Channel thread-safety in Java Client API Guide: Channel instances are safe for use by multiple threads. Requests into a Channel are serialized, with only one thread being able to run a command on the Channel at a time. Even so, applications should prefer using a Channel per thread instead of sharing the same Channel across multiple threads. There is no direct relation between Channel and Queue. A Channel is used to send AMQP commands to the broker. This can be the creation of a queue or similar, but these concepts are not tied together. Each Consumer runs in its own thread allocated from the consumer thread pool. If multiple Consumers are subscribed to the same Queue, the broker uses round-robin to distribute the messages between them equally. See Tutorial two: "Work Queues". It is also possible to attach the same Consumer to multiple Queues. You can understand Consumers as callbacks. These are called everytime a message arrives on a Queue the Consumer is bound to. For the case of the Java Client, each Consumers has a method handleDelivery(...), which represents the callback method. What you typically do is, subclass DefaultConsumer and override handleDelivery(...). Note: If you attach the same Consumer instance to multiple queues, this method will be called by different threads. So take care of synchronization if necessary.
RabbitMQ
18,418,936
237
I've installed the latest RabbitMQ server (rabbitmq-server-3.3.0-1.noarch.rpm) on a fresh Centos 5.10 VM according to the instructions on the official site. I've done this many times before during development and never had any issues. However, this time I cannot log into the management web interface using the default guest/guest user. In the logs, I see the following: =ERROR REPORT==== 4-Apr-2014::00:55:15 === webmachine error: path="api/whoami" "Unauthorized" What could be causing this?
It's new features since the version 3.3.0 http://www.rabbitmq.com/release-notes/README-3.3.0.txt server ------ ... 25603 prevent access using the default guest/guest credentials except via localhost. If you want enable the guest user read this or this RabbitMQ 3.3.1 can not login with guest/guest # remove guest from loopback_users in rabbitmq.config like this [{rabbit, [{loopback_users, []}]}]. # It is danger for default user and default password for remote access # better to change password rabbitmqctl change_password guest NEWPASSWORD If you want create a new user with admin grants: rabbitmqctl add_user test test rabbitmqctl set_user_tags test administrator rabbitmqctl set_permissions -p / test ".*" ".*" ".*" Now you can access using test test.
RabbitMQ
22,850,546
230
I installed rabbitmqadmin and was able to list all the exchanges and queues. How can I use rabbitmqadmin or rabbitmqctl to delete all the queues.
First, list your queues: rabbitmqadmin list queues name Then from the list, you'll need to manually delete them one by one: rabbitmqadmin delete queue name='queuename' Because of the output format, doesn't appear you can grep the response from list queues. Alternatively, if you're just looking for a way to clear everything (read: reset all settings, returning the installation to a default state), use: rabbitmqctl stop_app rabbitmqctl reset # Be sure you really want to do this! rabbitmqctl start_app
RabbitMQ
11,459,676
227
How do I delete all messages from a single queue using the cli? I have the queue name and I want to clean it.
you can directly run this command sudo rabbitmqctl purge_queue queue_name
RabbitMQ
5,313,027
183
How can I verify which version of rabbitmq is running on a server? Is there a command to verify that rabbitmq is running?
Use this command: sudo rabbitmqctl status and look for line that looks like this: {rabbit,"RabbitMQ","2.6.1"},
RabbitMQ
7,593,269
174
What ports does RabbitMQ Server use or need to have open on the firewall for a cluster of nodes? My /usr/lib/rabbitmq/bin/rabbitmq-env is set below which I'm assuming are needed (35197). SERVER_ERL_ARGS="+K true +A30 +P 1048576 \ -kernel inet_default_connect_options [{nodelay,true}] \ -kernel inet_dist_listen_min 35197 \ -kernel inet_dist_listen_max 35197" I haven't touched the rabbitmq.config to set a custom tcp_listener so it should be listening on the default 5672. Here are the relevant netstat lines: tcp 0 0 0.0.0.0:4369 0.0.0.0:* LISTEN 728/epmd tcp 0 0 0.0.0.0:35197 0.0.0.0:* LISTEN 5126/beam tcp6 0 0 :::5672 :::* LISTEN 5126/beam My questions are: for other nodes to be able to connect to the cluster, do all 3 ports 4369, 5672 and 35197 need to be open? Why isn't 5672 running on tcp and not just tcp6?
PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work. PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes RabbitMQ Management console: PORT 15672 for RabbitMQ version 3.x PORT 55672 for RabbitMQ pre 3.x Make sure that the rabbitmq_management plugin is enabled, otherwise you won't be able to access management console on those ports. PORT 5672 RabbitMQ main port (AMQP) PORT 5671 TLS-encrypted AMQP (if enabled) For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672. For any servers that want to use the message queue, only 5672 (or possibly 5671) is required.
RabbitMQ
12,792,856
160
I am trying to understand what JMS and how it is connected to AMQP terminology. I know JMS is an API and AMQP is a protocol. Here are my assumptions (and questions as well) RabbitMQ uses AMQP protocol (rather implements AMQP protocol) Java clients need to use AMQP protocol client libraries to connect / use RabbitMQ Where does JMS API come into play here? JMS API should use AMQP client libraries to connect to RabbitMQ? Usually we use JMS to connect Message brokers like RabbitMQ, ActiveMQ, etc. Then what is the default protocol used here instead of AMQP? Some of the above may be dumb. :-) But trying to wrap my head around it.
Your question is a bit messy but Let's see its bits one by one. General concept: The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914. It is a messaging standard that allows application components based on the Java Enterprise Edition (Java EE) to create, send, receive, and read messages. It allows the communication between different components of a distributed application to be loosely coupled, reliable, and asynchronous. Now (from Wikipedia): The Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for message-oriented middleware. The defining features of AMQP are message orientation, queuing, routing (including point-to-point and publish-and-subscribe), reliability and security. And the most important thing (again from Wikipedia): Unlike JMS, which merely defines an API, AMQP is a wire-level protocol. A wire-level protocol is a description of the format of the data that is sent across the network as a stream of octets. Consequently any tool that can create and interpret messages that conform to this data format can interoperate with any other compliant tool irrespective of implementation language Some important things you should know: Keep in mind that AMQP is a messaging technology that do not implement the JMS API. JMS is API and AMQP is a protocol.So it doesn't make sense to say that what is default protocol of JMS, of course client applications use HTTP/S as the connection protocol when invoking a WebLogic Web Service. JMS is only a API spec. It doesn't use any protocol. A JMS provider (like ActiveMQ) could be using any underlying protocol to realize the JMS API. For ex: Apache ActiveMQ can use any of the following protocols: AMQP, MQTT, OpenWire, REST(HTTP), RSS and Atom, Stomp, WSIF, WS Notification, XMPP. I suggest you read Using JMS Transport as the Connection Protocol. Good Luck :)
RabbitMQ
15,150,133
157
I'm getting confused between these two types of messages in RabbitMQ. I've seen that some of my queues have 0 "Unacked" and 1000 "Ready" messages, while some have 1000 "Unacked" and 0 "Ready" messages. What's the difference between them? And how can I know how many of the messages are read by the consumer(s)?
A message is Ready when it is waiting to be processed. When a consumer connects to the queue it gets a batch of messages to process. The amount is given in the prefetch size. While this consumer is working on the messages they get the status unacked. Unacked means that the consumer has promised to process them but has not acknowledged that they are processed. When the consumer crashed the queue knows which messages are to be delivered again when the consumer comes online. When you have multiple consumers the messages are distributed among them.
RabbitMQ
31,915,773
145
I need to create a queue for processing. The queue itself is relatively low-volume. There might be about 1,000 writes to it per hour. The execution of each task might take about a minute each, and are processed almost as soon as the item is added to the queue. Is there any reason that I might want to implement RabbitMQ instead of something off-the-shelf like Amazon SQS? What are some reasons why an application would need its own queueing system instead of something like SQS?
Here are a few factors to help you decide which one to go for: RabbitMQ is FIFO by default. Amazon SQS queues can optionally be set to FIFO. You can setup your own server with RabbitMQ but not in the case of Amazon SQS so the cost gets involved here. Setting up your own server will require good knowledge of the subject so that you do not leave any corner untouched. This is not the case with Amazon SQS as it is pretty quick to get started with. Your own RabbitMQ server means maintenance cost down the line which is not the case with Amazon SQS.
RabbitMQ
28,687,295
141
I am getting below exception org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. Configuration: RabbitMQ 3.3.5 on windows On Config file in %APPDATA%\RabbitMQ\rabbit.config I have done below change as per https://www.rabbitmq.com/access-control.html [{rabbit, [{loopback_users, []}]}]. I also tried creating a user/pwd - test/test doesn't seem to make it work. Tried the Steps from this post. Other Configuration Details are as below: Tomcat hosted Spring Application Context: <!-- Rabbit MQ configuration Start --> <!-- Connection Factory --> <rabbit:connection-factory id="rabbitConnFactory" virtual-host="/" username="guest" password="guest" port="5672"/> <!-- Spring AMQP Template --> <rabbit:template id="rabbitTemplate" connection-factory="rabbitConnFactory" routing-key="ecl.down.queue" queue="ecl.down.queue" /> <!-- Spring AMQP Admin --> <rabbit:admin id="admin" connection-factory="rabbitConnFactory"/> <rabbit:queue id="ecl.down.queue" name="ecl.down.queue" /> <rabbit:direct-exchange name="ecl.down.exchange"> <rabbit:bindings> <rabbit:binding key="ecl.down.key" queue="ecl.down.queue"/> </rabbit:bindings> </rabbit:direct-exchange> In my Controller Class @Autowired RmqMessageSender rmqMessageSender; //Inside a method rmqMessageSender.submitToECLDown(orderInSession.getOrderNo()); In My Message sender: import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("messageSender") public class RmqMessageSender { @Autowired AmqpTemplate rabbitTemplate; public void submitToRMQ(String orderId){ try{ rabbitTemplate.convertAndSend("Hello World"); } catch (Exception e){ LOGGER.error(e.getMessage()); } } } Above exception Block gives below Exception org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. Error Log =ERROR REPORT==== 7-Nov-2014::18:04:37 === closing AMQP connection <0.489.0> (10.1.XX.2XX:52298 -> 10.1.XX.2XX:5672): {handshake_error,starting,0, {amqp_error,access_refused, "PLAIN login refused: user 'guest' can only connect via localhost", 'connection.start_ok'}} Pls find below the pom.xml entry <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>1.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-amqp</artifactId> <version>4.0.4.RELEASE</version> </dependency> Please let me know if you have any thoughts/suggestions
I am sure what Artem Bilan has explained here might be one of the reasons for this error: Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the but the solution for me was that I logged in to rabbitMQ admin page (http://localhost:15672/#/users) with the default user name and password which is guest/guest then added a new user and for that new user I enabled the permission to access it from virtual host and then used the new user name and password instead of default guest and that cleared the error.
RabbitMQ
26,811,924
136
From my understanding, Celery is a distributed task queue, which means the only thing that it should do is dispatching tasks/jobs to others servers and get the result back. RabbitMQ is a message queue, and nothing more. However, a worker could just listen to the MQ and execute the task when a message is received. This achieves exactly what Celery offers, so why need Celery at all?
You are right, you don't need Celery at all. When you are designing a distributed system there are a lot of options and there is no right way to do things that fits all situations. Many people find that it is more flexible to have pools of message consumers waiting for a message to appear on their queue, doing some work, and sending a message when the work is finished. Celery is a framework that wraps up a whole lot of things in a package but if you don't really need the whole package, then it is better to set up RabbitMQ and implement just what you need without all the complexity. In addition, RabbitMQ can be used in many more scenarios besides the task queue scenario that Celery implements. But if you do choose Celery, then think twice about RabbitMQ. Celery's message queueing model is simplistic and it is really a better fit for something like Redis than for RabbitMQ. Rabbit has a rich set of options that Celery basically ignores.
RabbitMQ
9,077,687
133
This was probably asked already, but so far I can't find any detailed explanation at all, and the existing documentation seems as if it was written for some kind on psychic who supposed to know everything. As per this manual, I added the container docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:latest Then I checked it to receive the container ip docker inspect some-rabbit Checked ports with docker ps And tried to connect in the browser with this formula https://{container-ip}:{port} It did't work. Am I'm doing something wrong, or maybe I am supposed to add something additional, like a container for apache or other stuff? EDIT As I understand, after creating some-rabbit container, now I need to run Dockerfile to create image? (This whole thing is confusing to me). How am I supposed to do that? I mean, I saw command docker build -f /path/to/a/Dockerfile but if for example I placed the Dockerfile in second path D:\Docker\rabbitmq, how I supposed to get there? (the path doesn't seems to be recognized)
You are using the wrong image which doesn't have the rabbitmq_management plugin enabled. Change rabbitmq:latest to rabbitmq:management. On dockerhub they are using the command: docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3-management If you want to go to the UI on localhost:15672 make sure to expose the port by adding -p 15672:15672 to the above command. The management image is just the rabbitmq latest image with the management plugin enabled. Here is the dockerfile for rabbitmq:management FROM rabbitmq RUN rabbitmq-plugins enable --offline rabbitmq_management EXPOSE 15671 15672
RabbitMQ
47,290,108
132
We are defining an architecture to collect log information by Logstash shippers which are installed in various machines and index the data in one elasticsearch server centrally and use Kibana as the graphical layer. We need a reliable messaging system in between Logstash shippers and elasticsearch to grantee the delivery. What factors should be considered when selecting Redis over RabbitMQ as a data broker/messaging system in between Logstash shippers and the elasticsearch or vice versa?
After evaluating both Redis and RabbitMQ I chose RabbitMQ as our broker for the following reasons: RabbitMQ allows you to use a built in layer of security by using SSL certificates to encrypt the data that you are sending to the broker and it means that no one will sniff your data and have access to your vital organizational data. RabbitMQ is a very stable product that can handle large amounts of events per seconds and many connections without being the bottle neck. Regarding scaling, RabbitMQ has a built in cluster implementation that you can use in addition to a load balancer in order to implement a redundant broker environment. Is my RabbitMQ cluster Active Active or Active Passive? Now to the weaker point of using RabbitMQ: most Logstash shippers do not support RabbitMQ but on the other hand, the best one, named Beaver, has an implementation that will send data to RabbitMQ without a problem. The implementation that Beaver has with RabbitMQ in its current version is a little slow on performance (for my purposes) and was not able to handle the rate of 3000 events/sec from one server and from time to time the service crashed. Right now I am working on a fix that will solve the performance problem for RabbitMQ and make the Beaver shipper more stable. The first solution is to add more processes that can run simultaneously and will give the shipper more power. The second solution is to change Beaver to send data to RabbitMQ asynchronously which theoretically should be much faster. I hope that I’ll finish implementing both solutions by the end of this week. You can follow the issue here: https://github.com/josegonzalez/python-beaver/issues/323 And check the pull request here: https://github.com/josegonzalez/python-beaver/pull/324 If you have more questions feel free to leave a comment.
RabbitMQ
29,539,443
124
What is the basic difference between stream processing and traditional message processing? As people say that kafka is good choice for stream processing but essentially kafka is a messaging framework similar to ActivMQ, RabbitMQ etc. Why do we generally not say that ActiveMQ is good for stream processing as well. Is it the speed at which messages are consumed by the consumer determines if it is a stream?
In traditional message processing, you apply simple computations on the messages -- in most cases individually per message. In stream processing, you apply complex operations on multiple input streams and multiple records (ie, messages) at the same time (like aggregations and joins). Furthermore, traditional messaging systems cannot go "back in time" -- ie, they automatically delete messages after they got delivered to all subscribed consumers. In contrast, Kafka keeps the messages as it uses a pull-based model (ie, consumers pull data out of Kafka) for a configurable amount of time. This allows consumers to "rewind" and consume messages multiple times -- or if you add a new consumer, it can read the complete history. This makes stream processing possible, because it allows for more complex applications. Furthermore, stream processing is not necessarily about real-time processing -- it's about processing infinite input streams (in contrast to batch processing, which is applied to finite inputs). And Kafka offers Kafka Connect and Streams API -- so it is a stream-processing platform and not just a messaging/pub-sub system (even if it uses this in its core).
RabbitMQ
41,744,506
121
Currently i am starting RabbitMQ Docker container using the default RabbitMQ image from DockerHub. Using the following commands. docker run --restart=always \ -d \ -e RABBITMQ_NODENAME=rabbitmq \ -v /opt/docker/rabbitmq/data:/var/lib/rabbitmq/mnesia/rabbitmq \ -p 5672:5672 \ -p 15672:15672 \ --name rabbitmq rabbitmq:3-management I have a need where i want to provide defaults users / and virtual-hosts when the image is first started. For example to create a default 'test-user'. Currently i have to do that manually by using the management plugin and adding the users / virtual-hosts via the web ui. Is there a way i can provide default settings when starting the RabbitMQ image?
You can create a simple Dockerfile that extends the functionality of the basic image and creates a default user. The Docker file you need is the following: FROM rabbitmq # Define environment variables. ENV RABBITMQ_USER user ENV RABBITMQ_PASSWORD user ENV RABBITMQ_PID_FILE /var/lib/rabbitmq/mnesia/rabbitmq ADD init.sh /init.sh RUN chmod +x /init.sh EXPOSE 15672 # Define default command CMD ["/init.sh"] And the init.sh: #!/bin/sh # Create Rabbitmq user ( rabbitmqctl wait --timeout 60 $RABBITMQ_PID_FILE ; \ rabbitmqctl add_user $RABBITMQ_USER $RABBITMQ_PASSWORD 2>/dev/null ; \ rabbitmqctl set_user_tags $RABBITMQ_USER administrator ; \ rabbitmqctl set_permissions -p / $RABBITMQ_USER ".*" ".*" ".*" ; \ echo "*** User '$RABBITMQ_USER' with password '$RABBITMQ_PASSWORD' completed. ***" ; \ echo "*** Log in the WebUI at port 15672 (example: http:/localhost:15672) ***") & # $@ is used to pass arguments to the rabbitmq-server command. # For example if you use it like this: docker run -d rabbitmq arg1 arg2, # it will be as you run in the container rabbitmq-server arg1 arg2 rabbitmq-server $@ This script also initialize and expose the RabbitMQ webadmin at port 15672.
RabbitMQ
30,747,469
113
What are the allowed types of messages (strings, bytes, integers, etc.)? What is the maximum size of a message? What is the maximum number of queues and exchanges?
Theoretically anything can be stored/sent as a message. You actually don't want to store anything on the queues. The system works most efficiently if the queues are empty most of the time. You can send anything you want to the queue with two preconditions: The thing you are sending can be converted to and from a bytestring The consumer knows exactly what it is getting and how to convert it to the original object Strings are pretty easy, they have a built in method for converting to and from bytes. If you know it is a string then you know how to convert it back. The best option is to use a markup string like XML, JSON, or YML. This way you can convert objects to Strings and back again to the original objects; they work across programming languages so your consumer can be written in a different language to your producer as long as it knows how to understand the object. I work in Java. I want to send complex messages with sub objects in the fields. I use my own message object. The message object has two additional methods toBytes and fromBytes that convert to and from the bytestream. I use routing keys that leave no doubt as to what type of message the consumer is receiving. The message is Serializable. This works fine, but is limiting as I can only use it with other Java programs. The size of the message is limited by the memory on the server, and if it is persistent then also the free HDD space too. You probably do not want to send messages that are too big; it might be better to send a reference to a file or DB. You might also want to read up on their performance measures: http://www.rabbitmq.com/blog/2012/04/17/rabbitmq-performance-measurements-part-1/ http://www.rabbitmq.com/blog/2012/04/25/rabbitmq-performance-measurements-part-2/ Queues are pretty light weight, you will most likely be limited by the number of connections you have. It will depend on the server most likely. Here is some info on a similiar question: http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2009-February/003042.html
RabbitMQ
18,353,898
111
Using rabbitmq, we can install management plugin. Then we access via browser using http://localhost:55672/ using guest:guest. The problem is, I can not login anymore because i changed password and entered blank for role. Is there any way to reset user for rabbitmq management?
You can access the user-management with rabbitmqctl and use the command: add_user {username} {password} or more preferably maybe edit an existing user, or set the permissions for the new user with: set_permissions [-p vhostpath] {user} {conf} {write} {read} For example use the following commands: (it is important to perform these three steps even when creating a new user, if you want to be able to login to the UI console and for your programs to work without facing any permission issues) rabbitmqctl add_user newadmin s0m3p4ssw0rd rabbitmqctl set_user_tags newadmin administrator rabbitmqctl set_permissions -p / newadmin ".*" ".*" ".*" ...to create a new administrator user with full access to the default / vhost. You can find all this on the RabbitMQ homepage, and more specifically on this page
RabbitMQ
14,699,873
107
I have a few queues running with RabbitMQ. A few of them are of no use now, how can I delete them? Unfortunately I had not set the auto_delete option. If I set it now, will it be deleted? Is there a way to delete those queues now?
If you do not care about the data in management database; i.e. users, vhosts, messages etc., and neither about other queues, then you can reset via commandline by running the following commands in order: WARNING: In addition to the queues, this will also remove any users and vhosts, you have configured on your RabbitMQ server; and will delete any persistent messages rabbitmqctl stop_app rabbitmqctl reset rabbitmqctl start_app The rabbitmq documentation says that the reset command: Returns a RabbitMQ node to its virgin state. Removes the node from any cluster it belongs to, removes all data from the management database, such as configured users and vhosts, and deletes all persistent messages. So, be careful using it.
RabbitMQ
6,742,938
103
I am using RabbitMQ and I have a queue that holds email messages. My consumer service de-queues messages and attempts to send them. If, for any reason, my consumer cannot send the message, I would like to re-queue the message to send again. I realize I can do a basicNack and set the requeue flag to be true, however, I don't want to requeue the message indefinitely (say, if our email system goes down, I don't want to continuously requeue unsent messages). I would like to define a finite number of times that I can requeue the message to be sent again. I can't set a field on the email message object, however, when I dequeue it and send a nack. The updated field is not present on the message in the queue. Is there any other way in which I can approach this?
Update from 2023 based on quorum queue's way of poison message handling: Quorum queues keep track of the number of unsuccessful delivery attempts and expose it in the "x-delivery-count" header that is included with any redelivered message. They've also added a support of policies to limit re-deliveries: It is possible to set a delivery limit for a queue using a policy argument, delivery-limit. So given this new additions (and deprecation of classic queues) the original answer below might be no longer relevant for latest RabbitMQ versions. Original answer (before queue and stream queues were added): There are no such feature like retry attempts in RabbitMQ (as well as in AMQP protocol). Possible solution to implement retry attempts limit behavior: Redeliver message if it was not previously redelivered (check redelivered parameter on basic.deliver method - your library should have some interface for this) and drop it and then catch in dead letter exchange, then process somehow. Each time message cannot be processed publish it again but set or increment/decrement header field, say x-redelivered-count (you can chose any name you like, though). To get control over redeliveries in this case you have to check the field you set whether it reaches some limit (top or bottom - 0 is my choise, a-la ttl in ip header from tcp/ip). Store message unique key (say uuid, but you have to set it manually when you publish message) in Redis, memcache or other storage, even in mysql alongside with redeliveries count and then on each redelivery increment/decrement this value until it reach the limit. (for real geeks) write plugin that will implement such behavior like you want. The pro of #3 is that redelivered message stay in queue head. This is important if you have long queue or if message order is important for you (note, that redeliveries will break strict messages order, see official docs for details or this question on SO). P.S.: There is similar answer in this topic, but in php. Look through it, maybe it helps you a bit (start reading it from words "There are multiple techniques to deal with cycle redeliver problem".
RabbitMQ
23,158,310
102
If I have RabbitMQ installed on my machine, is there a way to create a message queue from the command line and bind it to a certain exchange without using a client? I think it is not possible, but I want to be sure.
Summary: Other answers are good alternatives to what was asked for. Below are commands you can use from the command line. First, do all the necessary prep work, e.g. install rabbit, rabbitmqadmin, and rabbitctl. The idea is to use commands from rabbitmqctl and rabbitmqadmin. You can see some command examples: https://www.rabbitmq.com/management-cli.html Example Commands/Setup: The following commands should give you the majority if not all of what you need: # Get the cli and make it available to use. wget http://127.0.0.1:15672/cli/rabbitmqadmin chmod +x rabbitmqadmin mv rabbitmqadmin /etc/rabbitmq Add a user and permissions rabbitmqctl add_user testuser testpassword rabbitmqctl set_user_tags testuser administrator rabbitmqctl set_permissions -p / testuser ".*" ".*" ".*" Make a virtual host and Set Permissions rabbitmqctl add_vhost Some_Virtual_Host rabbitmqctl set_permissions -p Some_Virtual_Host guest ".*" ".*" ".*" Make an Exchange ./rabbitmqadmin declare exchange --vhost=Some_Virtual_Host name=some_exchange type=direct Make a Queue ./rabbitmqadmin declare queue --vhost=Some_Virtual_Host name=some_outgoing_queue durable=true Make a Binding ./rabbitmqadmin --vhost="Some_Virtual_Host" declare binding source="some_exchange" destination_type="queue" destination="some_incoming_queue" routing_key="some_routing_key" Alternative Way to Bind with Python The following is an alternative to command line binding, as I've had issues with it sometimes and found the following python code to be more reliable. #!/usr/bin/env python import pika rabbitmq_host = "127.0.0.1" rabbitmq_port = 5672 rabbitmq_virtual_host = "Some_Virtual_Host" rabbitmq_send_exchange = "some_exchange" rabbitmq_rcv_exchange = "some_exchange" rabbitmq_rcv_queue = "some_incoming_queue" rabbitmq_rcv_key = "some_routing_key" outgoingRoutingKeys = ["outgoing_routing_key"] outgoingQueues = ["some_outgoing_queue "] # The binding area credentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_password) connection = pika.BlockingConnection(pika.ConnectionParameters(rabbitmq_host, rabbitmq_port, rabbitmq_virtual_host, credentials)) channel = connection.channel() channel.queue_bind(exchange=rabbitmq_rcv_exchange, queue=rabbitmq_rcv_queue, routing_key=rabbitmq_rcv_key) for index in range(len(outgoingRoutingKeys)): channel.queue_bind(exchange=rabbitmq_send_exchange, queue=outgoingQueues[index], routing_key=outgoingRoutingKeys[index]) The above can be run as part of a script using python. Notice I put the outgoing stuff into arrays, which will allow you to iterate through them. This should make things easy for deploys. Last Thoughts I think the above should get you moving in the right direction, use google if any specific commands don't make sense or read more with rabbitmqadmin help subcommands. I tried to use variables that explain themselves.
RabbitMQ
4,545,660
92
This seems like a question that should be easily be googleable. It is not though. Can anybody help? How do I create a new user for rabbitmq?
I have found this very useful This adds a new user and password rabbitmqctl add_user username password This makes the user a administrator rabbitmqctl set_user_tags username administrator This sets permissions for the user rabbitmqctl set_permissions -p / username ".*" ".*" ".*" See more here https://www.rabbitmq.com/rabbitmqctl.8.html#User_Management
RabbitMQ
40,436,425
90
I need to choose a new Queue broker for my new project. This time I need a scalable queue that supports pub/sub, and keeping message ordering is a must. I read Alexis comment: He writes: "Indeed, we think RabbitMQ provides stronger ordering than Kafka" I read the message ordering section in rabbitmq docs: "Messages can be returned to the queue using AMQP methods that feature a requeue parameter (basic.recover, basic.reject and basic.nack), or due to a channel closing while holding unacknowledged messages...With release 2.7.0 and later it is still possible for individual consumers to observe messages out of order if the queue has multiple subscribers. This is due to the actions of other subscribers who may requeue messages. From the perspective of the queue the messages are always held in the publication order." If I need to handle messages by their order, I can only use rabbitMQ with an exclusive queue to each consumer? Is RabbitMQ still considered a good solution for ordered message queuing?
Well, let's take a closer look at the scenario you are describing above. I think it's important to paste the documentation immediately prior to the snippet in your question to provide context: Section 4.7 of the AMQP 0-9-1 core specification explains the conditions under which ordering is guaranteed: messages published in one channel, passing through one exchange and one queue and one outgoing channel will be received in the same order that they were sent. RabbitMQ offers stronger guarantees since release 2.7.0. Messages can be returned to the queue using AMQP methods that feature a requeue parameter (basic.recover, basic.reject and basic.nack), or due to a channel closing while holding unacknowledged messages. Any of these scenarios caused messages to be requeued at the back of the queue for RabbitMQ releases earlier than 2.7.0. From RabbitMQ release 2.7.0, messages are always held in the queue in publication order, even in the presence of requeueing or channel closure. (emphasis added) So, it is clear that RabbitMQ, from 2.7.0 onward, is making a rather drastic improvement over the original AMQP specification with regard to message ordering. With multiple (parallel) consumers, order of processing cannot be guaranteed. The third paragraph (pasted in the question) goes on to give a disclaimer, which I will paraphrase: "if you have multiple processors in the queue, there is no longer a guarantee that messages will be processed in order." All they are saying here is that RabbitMQ cannot defy the laws of mathematics. Consider a line of customers at a bank. This particular bank prides itself on helping customers in the order they came into the bank. Customers line up in a queue, and are served by the next of 3 available tellers. This morning, it so happened that all three tellers became available at the same time, and the next 3 customers approached. Suddenly, the first of the three tellers became violently ill, and could not finish serving the first customer in the line. By the time this happened, teller 2 had finished with customer 2 and teller 3 had already begun to serve customer 3. Now, one of two things can happen. (1) The first customer in line can go back to the head of the line or (2) the first customer can pre-empt the third customer, causing that teller to stop working on the third customer and start working on the first. This type of pre-emption logic is not supported by RabbitMQ, nor any other message broker that I'm aware of. In either case, the first customer actually does not end up getting helped first - the second customer does, being lucky enough to get a good, fast teller off the bat. The only way to guarantee customers are helped in order is to have one teller helping customers one at a time, which will cause major customer service issues for the bank. It is not possible to ensure that messages get handled in order in every possible case, given that you have multiple consumers. It doesn't matter if you have multiple queues, multiple exclusive consumers, different brokers, etc. - there is no way to guarantee a priori that messages are answered in order with multiple consumers. But RabbitMQ will make a best-effort.
RabbitMQ
21,363,302
89
I have RabbitMQ installed and started. The service is running as well. However, when I try to open the management interface in firefox, I get this error: Firefox can't establish a connection to the server at localhost:#####. (##### being several port numbers i tried). I checked the ports and made sure that they were correct as well as trying to reinstall RabbitMQ. Any ideas on how to fix this?
I think you should check a few things: the management plugin is not enabled by default, you need to run the below command to enable it: (see https://www.rabbitmq.com/management.html) rabbitmq-plugins enable rabbitmq_management Also this runs on port 15672 by default, it is possible the server/network is blocking this port. You will need to check that the port is open.
RabbitMQ
23,500,014
83
I'm doing real time live web app development. Browser users should be able to communicate with eachother through a node.js server. One of the user writes a message and all other users will get it. I don't quite get how RabbitMQ works. But from quick reading it seems that it handles publication/subscription of messages. A user (in a browser) publishes something and subscribers (in other browsers) get that message. Isn't that what Socket.io is doing with websockets? Here are my questions: What are the advantages/disadvantages for each one of them? Can Socket.io replace RabbitMQ? Are there scenarios I need RabbitMQ for web apps where Socket.io doesn't suffice?
Update Are there scenarios I need RabbitMQ for web apps where Socket.io doesn't suffice? Browser users should be able to communicate with eachother through a node.js server. One of the user writes a message and all other users will get it. When you only have these simple requirements then socket.io alone will be enough.. You only need a message queue when you want to process your jobs(heavy) offline and in a controlled manner. http://en.wikipedia.org/wiki/Message_queue: Message queues provide an asynchronous communications protocol, meaning that the sender and receiver of the message do not need to interact with the message queue at the same time. This sentence needs to sink in. The producer (one process) puts a job into the queue and the consumer consumes by taking the job from the queue. The consumer, most times, are multiple processes that consume multiple jobs concurrently. The consumers are unable to tell from each other, what jobs they are consuming. This makes the queue a First-In-First-Out (FIFO) data structure. That's I think an important property of the queue. The First-In-First-Out property although with an advanced message queue like beanstalkd you can give jobs priorities. I hope this makes any sense at all ;) I'm doing real time live web app development. Could you explain a little better so that we can give you a better answer? I don't quite get how RabbitMQ works. But from quick reading it seems that it handles publication/subscription of messages. See the quote about message queue below. Let it sink in for a while. You could also read the WIKI about message queues. A user (in a browser) publishes something and subscribers (in other browsers) get that message. Isn't that what Socket.io is doing with websockets? Socket.io supports a lot of different transports(also websockets) and it should because websockets are not supported by the most browsers. But for example Google Chrome does already support websockets. I believe that websockets are the transport of the future(but not yet!). When you look at Socket.io's browser support page you will notice that Socket.io does support all the major browsers(some even ancient). The nice thing is that it wraps this around a nice API. What are the advantages/disadvantages for each one of them? You are comparing apples to oranges so comparing that is kind of strange. RabbitMQ http://www.rabbitmq.com/tutorials/tutorial-one-python.html: RabbitMQ is a message broker. The principal idea is pretty simple: it accepts and forwards messages. You can think about it as a post office: when you send mail to the post box you're pretty sure that Mr. Postman will eventually deliver the mail to your recipient. Using this metaphor RabbitMQ is a post box, a post office and a postman. Advantages It is a pretty good message queue. Personally I would use redis or beanstalkd. Disadvantages: Is not really for "browsers". Socket.io http://socket.io/: Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. Advantages It is for browser Disadvantages It is not a message queue. Can Socket.io replace RabbitMQ? No you can't because they are two completely different things. You are comparing apples to oranges. You should try to comprehend both descriptions from the sites I quoted.
RabbitMQ
6,636,213
83
I am trying to learn messaging system. I have found that RabbitMq and NServiceBus are using together in few places. My questions are If I am using the RabbitMQ then why do i need NServiceBus? and vice versa What NServiceBus can do but RabbitMQ or Kafka cannot? Can I use NServiceBus and kafka together? Or Apache-Kafka does not require NServiceBus
Years ago, I asked myself the same question. I was looking at NServiceBus to work with a different message queue, but the question was the same. I decided not to use NServiceBus. 6 Month later, I realized I had re-built half of what NServiceBus did... only much more poorly. The equivalent question of why would you need NServiceBus with RabbitMQ, is to ask why you would need the .NET Framework with ASP.NET MVC, or WinForms, or XAML, or any of the built-in libraries that .NET ships with, when you have the Common Language Runtime. Shouldn't the CLR be enough, after all? Of course not. Having the runtime on which code can execute - the MSIL interpreter and execution engine - is not nearly enough to be productive. Sure, you can write command-line applications that take input and produce output. But try to build a real application without the common libraries - without the built-in SQL Server drivers; without any 3rd party controls or libraries. Build a Windows Desktop app without the System.Windows namespace. You need those libraries to give you collections, and database access, and window objects and UI controls. Similarly, RabbitMQ gives you everything you need to get started and working, but not enough to maintain productivity. Sure, you can grab the .NET driver for RabbitMQ and start producing and consuming messages. For a while, this will work just fine. Pretty soon, you'll find yourself creating a wrapper around the driver, so you can reduce the amount of code you need to write. Then you'll find yourself needing to deal with ack vs nack, and you'll create a simple API for that. Then the need for dead-letter queues will pop up with nack calls, and you'll wrap that up in your API - simplified compared to the rabbitmq driver, of course. Eventually, you'll want to deal with poison messages - messages that are malformed and causing exceptions. Once again, you don't want to write one-off code for this, so you'll write a library to handle it. The list goes on and on. 6 months from now, you'll find yourself working with a half-written, barely specified, untestable library that only mimics the value and capabilities of NServiceBus (or MassTransit or whatever other service bus library you choose). I won't say you have to use NServiceBus. And I would say you should learn how RabbitMQ works, without it. But once you get beyond the basics of sending and receiving messages, the value of NServiceBus and other service bus implementations, becomes very apparent, very quickly.
RabbitMQ
38,103,412
82
OS: Mac OSX 10.9 I have rabbitmq installed via home brew and when I go to /usr/local/sbin and run rabbitmq-server it states that: rabbitmq-server: command not found even as sudo it states the same error. How do I get rabbitmq to start if it's not a command? I have also tried chmod +x rabbitmq-server in that directory to get it be an executable, same issue.
From the docs: The RabbitMQ server scripts are installed into /usr/local/sbin. This is not automatically added to your path, so you may wish to add PATH=$PATH:/usr/local/sbin to your .bash_profile or .profile. The server can then be started with rabbitmq-server. All scripts run under your own user account. Sudo is not required. You should be able to run /usr/local/sbin/rabbitmq-server or add it to your path to run it anywhere. Your command failed because, by default, . is not on your $PATH. You went to the right directory (/usr/local/sbin) and wanted to run the rabbitmq-server that existed and had exec permissions, but by typing rabbitmq-server as a command Unix only searches for that command on your $PATH directories - which didn't include /usr/local/sbin. What you wanted to do can be achieved by typing ./rabbitmq-server - say, execute the rabbitmq-server program that is in the current directory. That's analogous to running /usr/local/sbin/rabbitmq-server from everywhere - . represents your current directory, so it's the same as /usr/local/sbin in that context.
RabbitMQ
23,050,120
82
My rough understanding is that Redis is better if you need the in-memory key-value store feature, however I am not sure how that has anything to do with distributing tasks? Does that mean we should use Redis as a message broker IF we are already using it for something else?
I've used both recently (2017-2018), and they are both super stable with Celery 4. So your choice can be based on the details of your hosting setup. If you must use Celery version 2 or version 3, go with RabbitMQ. Otherwise... If you are using Redis for any other reason, go with Redis If you are hosting at AWS, go with Redis so that you can use a managed Redis as service If you hate complicated installs, go with Redis If you already have RabbitMQ installed, stay with RabbitMQ In the past, I would have recommended RabbitMQ because it was more stable and easier to setup with Celery than Redis, but I don't believe that's true any more. Update 2019 AWS now has a managed service that is equivalent to RabbitMQ called Amazon MQ, which could reduce the headache of running this as a service in production. Please comment below if you have any experience with this and celery.
RabbitMQ
43,264,838
77
We're trying to set up a basic directed queue system where a producer will generate several tasks and one or more consumers will grab a task at a time, process it, and acknowledge the message. The problem is, the processing can take 10-20 minutes, and we're not responding to messages at that time, causing the server to disconnect us. Here's some pseudo code for our consumer: #!/usr/bin/env python import pika import time connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body): long_running_task(connection) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='task_queue') channel.start_consuming() After the first task completes, an exception is thrown somewhere deep inside of BlockingConnection, complaining that the socket was reset. In addition, the RabbitMQ logs show that the consumer was disconnected for not responding in time (why it resets the connection rather than sending a FIN is strange, but we won't worry about that). We searched around a lot because we believed this was the normal use case for RabbitMQ (having a lot of long running tasks that should be split up among many consumers), but it seems like nobody else really had this issue. Finally we stumbled upon a thread where it was recommended to use heartbeats and to spawn the long_running_task() in a separate thread. So the code has become: #!/usr/bin/env python import pika import time import threading connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost', heartbeat_interval=20)) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) print ' [*] Waiting for messages. To exit press CTRL+C' def thread_func(ch, method, body): long_running_task(connection) ch.basic_ack(delivery_tag = method.delivery_tag) def callback(ch, method, properties, body): threading.Thread(target=thread_func, args=(ch, method, body)).start() channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='task_queue') channel.start_consuming() And this seems to work, but it's very messy. Are we sure that the ch object is thread safe? In addition, imagine that long_running_task() is using that connection parameter to add a task to a new queue (i.e. the first part of this long process is done, let's send the task on to the second part). So, the thread is using the connection object. Is that thread safe? More to the point, what's the preferred way of doing this? I feel like this is very messy and possibly not thread safe, so maybe we're not doing it right. Thanks!
For now, your best bet is to turn off heartbeats, this will keep RabbitMQ from closing the connection if you're blocking for too long. I am experimenting with pika's core connection management and IO loop running in a background thread but it's not stable enough to release. In pika v1.1.0 this is ConnectionParameters(heartbeat=0)
RabbitMQ
14,572,020
77
I am very new to RabbitMQ. I have set up a 'topic' exchange. The consumers may be started after the publisher. I'd like the consumers to be able to receive messages that have been sent before they were up, and that was not consumed yet. The exchange is set up with the following parameters: exchange_type => 'topic' durable => 1 auto_delete => 0 passive => 0 The messages are published with this parameter: delivery_mode => 2 Consumers use get() to retrieve the messages from the exchange. Unfortunately, any message published before any client was up is lost. I have used different combinations. I guess my problem is that the exchange does not hold messages. Maybe I need to have a queue between the publisher and the consumer. But this does not seem to work with a 'topic' exchange where messages are routed by a key. How should I proceed? I use the Perl binding Net::RabbitMQ (shouldn't matter) and RabbitMQ 2.2.0.
You need a durable queue to store messages if there are no connected consumers available to process the messages at the time they are published. An exchange doesn't store messages, but a queue can. The confusing part is that exchanges can be marked as "durable" but all that really means is that the exchange itself will still be there if you restart your broker, but it does not mean that any messages sent to that exchange are automatically persisted. Given that, here are two options: Perform an administrative step before you start your publishers to create the queue(s) yourself. You could use the web UI or the command line tools to do this. Make sure you create it as a durable queue so that it will store any messages that are routed to it even if there are no active consumers. Assuming your consumers are coded to always declare (and therefore auto-create) their exchanges and queues on startup (and that they declare them as durable), just run all your consumers at least once before starting any publishers. That will ensure that all your queues get created correctly. You can then shut down the consumers until they're really needed because the queues will persistently store any future messages routed to them. I would go for #1. There may not be many steps to perform and you could always script the steps required so that they could be repeated. Plus if all your consumers are going to pull from the same single queue (rather than have a dedicated queue each) it's really a minimal piece of administrative overhead. Queues are something to be managed and controlled properly. Otherwise you could end up with rogue consumers declaring durable queues, using them for a few minutes but never again. Soon after you'll have a permanently-growing queue with nothing reducing its size, and an impending broker apocalypse.
RabbitMQ
6,148,381
74
as opposed to writing your own library. We're working on a project here that will be a self-dividing server pool, if one section grows too heavy, the manager would divide it and put it on another machine as a separate process. It would also alert all connected clients this affects to connect to the new server. I am curious about using ZeroMQ for inter-server and inter-process communication. My partner would prefer to roll his own. I'm looking to the community to answer this question. I'm a fairly novice programmer myself and just learned about messaging queues. As i've googled and read, it seems everyone is using messaging queues for all sorts of things, but why? What makes them better than writing your own library? Why are they so common and why are there so many?
what makes them better than writing your own library? When rolling out the first version of your app, probably nothing: your needs are well defined and you will develop a messaging system that will fit your needs: small feature list, small source code etc. Those tools are very useful after the first release, when you actually have to extend your application and add more features to it. Let me give you a few use cases: your app will have to talk to a big endian machine (sparc/powerpc) from a little endian machine (x86, intel/amd). Your messaging system had some endian ordering assumption: go and fix it you designed your app so it is not a binary protocol/messaging system and now it is very slow because you spend most of your time parsing it (the number of messages increased and parsing became a bottleneck): adapt it so it can transport binary/fixed encoding at the beginning you had 3 machine inside a lan, no noticeable delays everything gets to every machine. your client/boss/pointy-haired-devil-boss shows up and tell you that you will install the app on WAN you do not manage - and then you start having connection failures, bad latency etc. you need to store message and retry sending them later on: go back to the code and plug this stuff in (and enjoy) messages sent need to have replies, but not all of them: you send some parameters in and expect a spreadsheet as a result instead of just sending and acknowledges, go back to code and plug this stuff in (and enjoy.) some messages are critical and there reception/sending needs proper backup/persistence/. Why you ask ? auditing purposes And many other use cases that I forgot ... You can implement it yourself, but do not spend much time doing so: you will probably replace it later on anyway.
RabbitMQ
1,823,705
74
What's the maximum number of queues that RabbitMQ can handle on a single server? Does it depend on RAM? Does it depends on erlang processes?
There are not any hard-coded limits inside RabbitMQ broker. The broker will utilize all available resources (unless you set limits on some of them, they are called watermarks in RabbitMQ terminology). There are some limitations put by Erlang itself, like maximum number of concurrent processes, but if you theoretically can reach them on single node then it is always good idea to use distributed features. There are a lot of discussions about RabbitMQ resource usage and limits, How many queues can one broker support on RabbitMQ mailing list Max messages allowed in a queue in RabbitMQ? on RabbitMQ mailing list Rabbitmq - Reasonable performance/scale expectations on Server Fault Is there a limit to the number of exchanges for rabbitmq? on Stack Overflow P.S. There are AMQP protocol limit though. They are described in section 4.9 Limitations The AMQP specifications impose these limits on future extensions of AMQP or protocols from the same wire-level format: Number of channels per connection: 16-bit channel number. Number of protocol classes: 16-bit class id. Number of methods per protocol class: 16-bit method id. The AMQP specifications impose these limits on data: Maximum size of a short string: 255 octets. Maximum size of a long string or field table: 32-bit size. Maximum size of a frame payload: 32-bit size. Maximum size of a content: 64-bit size. The server or client may also impose its own limits on resources such as number of simultaneous connections, number of consumers per channel, number of queues, etc. These do not affect interoperability and are not specified.
RabbitMQ
22,989,833
73
On a Windows 7 Enterprise machine, I made a fresh install of Erlang 17.4 and RabbitMQ 3.4.3 x64. The installation was successful and uneventful. I have not yet tried to create my first queue or exchange, but I already see trouble. This problem is similar to another SO post, but that other post appears to involve clustering, which I don't have. Furthermore, that other poster can circumvent his issue by restarting the RabbitMQ service; that approach does not work for me. My "nodedown" problem is evident at the RabbitMQ command prompt: C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.4.3\sbin>rabbitmqctl status Status of node rabbit@TPAJ05421843 ... Error: unable to connect to node rabbit@TPAJ05421843: nodedown DIAGNOSTICS attempted to contact: [rabbit@TPAJ05421843] rabbit@TPAJ05421843: * connected to epmd (port 4369) on TPAJ05421843 * epmd reports: node 'rabbit' not running at all other nodes on TPAJ05421843: ['RabbitMQ'] * suggestion: start the node current node details: - node name: 'rabbitmqctl-19884@TPAJ05421843' - home dir: H:\ - cookie hash: PD4QQCYrf0TME9vIko3Xuw== Based on the above, I chose to check the status of the node explicitly named 'RabbitMQ'. I get this: C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.4.3\sbin>rabbitmqctl -n RabbitMQ status Status of node 'RabbitMQ@TPAJ05421843' ... Error: unable to connect to node 'RabbitMQ@TPAJ05421843': nodedown DIAGNOSTICS attempted to contact: ['RabbitMQ@TPAJ05421843'] RabbitMQ@TPAJ05421843: * connected to epmd (port 4369) on TPAJ05421843 * epmd reports node 'RabbitMQ' running on port 59301 * TCP connection succeeded but Erlang distribution failed * suggestion: hostname mismatch? * suggestion: is the cookie set correctly? current node details: - node name: 'rabbitmqctl-23076@TPAJ05421843' - home dir: H:\ - cookie hash: PD4QQCYrf0TME9vIko3Xuw== Ok, this is barely better since at least it acknowledges 'RabbitMQ' running on port 59301. But what the heck could it mean that "Erlang distribution failed"? When I try to research this topic, I found articles saying "be sure you have matched cookies." Based on that I found this article, which claims the "cookie mismatch" does not pertain to me, because I have not created (nor intend to create) a RabbitMQ cluster. What should I do?
I had this same problem today. There were no cookie or firewall problems and windows reported that the service was running successfully. This is what finally fixed it: Run RabbitMQ sbin command prompt as administrator. Run "rabbitmq-service remove" Run "rabbitmq-service install" For some reason the service set up by the installer did not configure several registry entries. Running this set them correctly and allowed the service to run. One thing I noticed was that before I did this, there was no description of the service in the Windows Services view. After installing with the rabbitmq-service command, the description was visible. This might be a quick indicator if you are having the same problem.
RabbitMQ
28,258,392
71
Can I get the comparison between RabbitMQ and MSMQ. It will be helpful performance information on different factors are available.
I wrote a blog post a while back comparing MSMQ and RabbitMQ (among others): http://mikehadlow.blogspot.co.uk/2011/04/message-queue-shootout.html RabbitMQ gave slightly better performance than MSMQ, but both were comprehensively out performed by ZeroMQ. If performance is your main criteria, you should definitely look at ZeroMQ. It's worth noting that RabbitMQ and MSMQ are very different beasts. MSMQ is a simple store-and-forward queue. It doesn't provide any messaging patterns, such as pub/sub, or routing. For anything beyond simple point-to-point messaging you'd probably want to use a service bus library such as NServiceBus or MassTransit on top of MSMQ. RabbitMQ is a sophisticated server product that provides complex messaging patterns, topics and routing out-of-the-box. You also get centralized management and DR, something you'd have to implement yourself if you chose MSMQ.
RabbitMQ
17,806,977
70
Brief: Is there a way to install rabbitmq-plugins via a ubuntu package? Details: I have rabbitmq running ok in my ubuntu system, and now I'm trying to monitor what's going on via the management plugin. I'm following rabbitmq.com/management.html instructions, but can't execute rabbitmq-plugins enable rabbitmq_management because my system does not have rabbitmq-plugins installed. It's Ubuntu 1110, and came with rabbitmq installed as a package (aptitude install rabbitmq-server librabbitmq-dev). The config and the server are running fine (the installed version is 2.5.0). Thought that the plugin would get installed by installing "sudo aptitude install rabbitmq-plugins-common", but doing that does not install rabbitmq-plugins. Is there a package that will install the plugin? I'd like to avoid if possible having to purge the rabbitmq server that is running ok, and then reinstall it via a download + build from source, all just to get the plugin. Thanks.
If you are using Ubuntu 12.04 Steps are:-- My rabbitmq server version # dpkg -l rabbitmq-server Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Description +++-===================-===================-====================================================== ii rabbitmq-server 2.7.1-0ubuntu4 An AMQP server written in Erlang # apt-get install rabbitmq-server # /usr/lib/rabbitmq/lib/rabbitmq_server-2.7.1/sbin/rabbitmq-plugins list [ ] amqp_client 0.0.0 [ ] eldap 0.0.0-git [ ] erlando 0.0.0 [ ] mochiweb 1.3-rmq0.0.0-git [ ] rabbitmq_auth_backend_ldap 0.0.0 [ ] rabbitmq_auth_mechanism_ssl 0.0.0 [ ] rabbitmq_consistent_hash_exchange 0.0.0 [ ] rabbitmq_federation 0.0.0 [ ] rabbitmq_jsonrpc 0.0.0 [ ] rabbitmq_jsonrpc_channel 0.0.0 [ ] rabbitmq_jsonrpc_channel_examples 0.0.0 [ ] rabbitmq_management 0.0.0 [ ] rabbitmq_management_agent 0.0.0 [ ] rabbitmq_management_visualiser 0.0.0 [ ] rabbitmq_mochiweb 0.0.0 [ ] rabbitmq_shovel 0.0.0 [ ] rabbitmq_shovel_management 0.0.0 [ ] rabbitmq_stomp 0.0.0 [ ] rabbitmq_tracing 0.0.0 [ ] rfc4627_jsonrpc 0.0.0-git [ ] webmachine 1.7.0-rmq0.0.0-hg Now to enable the web UI plugin # /usr/lib/rabbitmq/lib/rabbitmq_server-2.7.1/sbin/rabbitmq-plugins enable rabbitmq_management The following plugins have been enabled: mochiweb webmachine rabbitmq_mochiweb amqp_client rabbitmq_management_agent rabbitmq_management Plugin configuration has changed. Restart RabbitMQ for changes to take effect. root@ubuntu:/usr/lib/rabbitmq/lib/rabbitmq_server-2.7.1/sbin# service rabbitmq-server restart Restarting rabbitmq-server: SUCCESS rabbitmq-server . root@ubuntu:/usr/lib/rabbitmq/lib/rabbitmq_server-2.7.1/sbin# /usr/lib/rabbitmq/lib/rabbitmq_server-2.7.1/sbin/rabbitmq-plugins list [e] amqp_client 0.0.0 [ ] eldap 0.0.0-git [ ] erlando 0.0.0 [e] mochiweb 1.3-rmq0.0.0-git [ ] rabbitmq_auth_backend_ldap 0.0.0 [ ] rabbitmq_auth_mechanism_ssl 0.0.0 [ ] rabbitmq_consistent_hash_exchange 0.0.0 [ ] rabbitmq_federation 0.0.0 [ ] rabbitmq_jsonrpc 0.0.0 [ ] rabbitmq_jsonrpc_channel 0.0.0 [ ] rabbitmq_jsonrpc_channel_examples 0.0.0 [E] rabbitmq_management 0.0.0 [e] rabbitmq_management_agent 0.0.0 [ ] rabbitmq_management_visualiser 0.0.0 [e] rabbitmq_mochiweb 0.0.0 [ ] rabbitmq_shovel 0.0.0 [ ] rabbitmq_shovel_management 0.0.0 [ ] rabbitmq_stomp 0.0.0 [ ] rabbitmq_tracing 0.0.0 [ ] rfc4627_jsonrpc 0.0.0-git [e] webmachine 1.7.0-rmq0.0.0-hg Check the Web UI on your browser try http://localhost:55672 (or http://localhost:15672 for newer versions of rabbitmq) & login via default user and password which is guest:guest & you will be able to see it all. Hope it helps.
RabbitMQ
8,548,983
66
The "RabbitMQ in Action" book on page 19 gives these descriptions of exclusive and auto-delete: exclusive - When set to true, your queue becomes private and can only be consumed by your app. This is useful when you need to limit a queue to only one consumer. auto-delete - The queue is automatically deleted when the last consumer unsubscribes. If you need a temporary queue used only by one consumer, combine auto-delete with exclusive. When the consumer disconnects, the queue will be removed. But as far as I can see when using exclusive, auto-delete is redundant. Only exclusive is needed. The RabbitMQ tutorial seems to say that is the case ...once we disconnect the consumer the queue should be deleted. There's an exclusive flag for that: result = channel.queue_declare(exclusive=True) There is no mention in that tutorial about auto-delete and sudo rabbitmqctl list_bindings seems to indicate that the queue is in fact deleted after the receiver goes away.
Well, it is true that exclusive queues will auto-delete when the consumer disconnects (see the documentation pasted below). However, there are cases when you want queues to be non-exclusive, yet still auto-delete (for example, if I want to add another consumer). exclusive Exclusive queues may only be accessed by the current connection, and are deleted when that connection closes. Passive declaration of an exclusive queue by other connections are not allowed. auto-delete If set, the queue is deleted when all consumers have finished using it. The last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. Applications can explicitly delete auto-delete queues using the Delete method as normal. Personally, I prefer to use neither of these parameters, instead opting for the RabbitMQ queue expiration parameter, which is better if I have a consumer disconnect and then re-connect immediately (or a short time) later; messages are not lost in this case. But, of course it all depends upon your application and requirements.
RabbitMQ
21,248,563
65
A little background. Very big monolithic Django application. All components use the same database. We need to separate services so we can independently upgrade some parts of the system without affecting the rest. We use RabbitMQ as a broker to Celery. Right now we have two options: HTTP Services using a REST interface. JSONRPC over AMQP to a event loop service My team is leaning towards HTTP because that's what they are familiar with but I think the advantages of using RPC over AMQP far outweigh it. AMQP provides us with the capabilities to easily add in load balancing, and high availability, with guaranteed message deliveries. Whereas with HTTP we have to create client HTTP wrappers to work with the REST interfaces, we have to put in a load balancer and set up that infrastructure in order to have HA etc. With AMQP I can just spawn another instance of the service, it will connect to the same queue as the other instances and bam, HA and load balancing. Am I missing something with my thoughts on AMQP?
At first, REST, RPC - architecture patterns, AMQP - wire-level and HTTP - application protocol which run on top of TCP/IP AMQP is a specific protocol when HTTP - general-purpose protocol, thus, HTTP has damn high overhead comparing to AMQP AMQP nature is asynchronous where HTTP nature is synchronous both REST and RPC use data serialization, which format is up to you and it depends of infrastructure. If you are using python everywhere I think you can use python native serialization - pickle which should be faster than JSON or any other formats. both HTTP+REST and AMQP+RPC can run in heterogeneous and/or distributed environment So if you are choosing what to use: HTTP+REST or AMQP+RPC, the answer is really subject of infrastructure complexity and resource usage. Without any specific requirements both solution will work fine, but i would rather make some abstraction to be able switch between them transparently. You told that your team familiar with HTTP but not with AMQP. If development time is an important time you got an answer. If you want to build HA infrastructure with minimal complexity I guess AMQP protocol is what you want. I had an experience with both of them and advantages of RESTful services are: they well-mapped on web interface people are familiar with them easy to debug (due to general purpose of HTTP) easy provide API to third-party services. Advantages of AMQP-based solution: damn fast flexible cost-effective (in resources usage meaning) Note, that you can provide RESTful API to third-party services on top of your AMQP-based API while REST is not a protocol but rather paradigm, but you should think about it building your AQMP RPC api. I have done it in this way to provide API to external third-party services and provide access to API on those part of infrastructure which run on old codebase or where it is not possible to add AMQP support. If I am right your question is about how to better organize communication between different parts of your software, not how to provide an API to end-users. If you have a high-load project RabbitMQ is damn good piece of software and you can easily add any number of workers which run on different machines. Also it has mirroring and clustering out of the box. And one more thing, RabbitMQ is build on top of Erlang OTP, which is high-reliable,stable platform ... (bla-bla-bla), it is good not only for marketing but for engineers too. I had an issue with RabbitMQ only once when nginx logs took all disc space on the same partition where RabbitMQ run. UPD (May 2018): Saurabh Bhoomkar posted a link to the MQ vs. HTTP article written by Arnold Shoon on June 7th, 2012, here's a copy of it: I was going through my old files and came across my notes on MQ and thought I’d share some reasons to use MQ vs. HTTP: If your consumer processes at a fixed rate (i.e. can’t handle floods to the HTTP server [bursts]) then using MQ provides the flexibility for the service to buffer the other requests vs. bogging it down. Time independent processing and messaging exchange patterns — if the thread is performing a fire-and-forget, then MQ is better suited for that pattern vs. HTTP. Long-lived processes are better suited for MQ as you can send a request and have a seperate thread listening for responses (note WS-Addressing allows HTTP to process in this manner but requires both endpoints to support that capability). Loose coupling where one process can continue to do work even if the other process is not available vs. HTTP having to retry. Request prioritization where more important messages can jump to the front of the queue. XA transactions – MQ is fully XA compliant – HTTP is not. Fault tolerance – MQ messages survive server or network failures – HTTP does not. MQ provides for ‘assured’ delivery of messages once and only once, http does not. MQ provides the ability to do message segmentation and message grouping for large messages – HTTP does not have that ability as it treats each transaction seperately. MQ provides a pub/sub interface where-as HTTP is point-to-point. UPD (Dec 2018): As noticed by @Kevin in comments below, it's questionable that RabbitMQ scales better then RESTful servies. My original answer was based on simply adding more workers, which is just a part of scaling and as long as single AMQP broker capacity not exceeded, it is true, though after that it requires more advanced techniques like Highly Available (Mirrored) Queues which makes both HTTP and AMQP-based services have some non-trivial complexity to scale at infrastructure level. After careful thinking I also removed that maintaining AMQP broker (RabbitMQ) is simpler than any HTTP server: original answer was written in Jun 2013 and a lot of changed since that time, but the main change was that I get more insight in both of approaches, so the best I can say now that "your mileage may vary". Also note, that comparing both HTTP and AMQP is apple to oranges to some extent, so please, do not interpret this answer as the ultimate guidance to base your decision on but rather take it as one of sources or as a reference for your further researches to find out what exact solution will match your particular case.
RabbitMQ
16,838,416
65
Rabbitmq server does not start, saying it's already running: $: rabbitmq-server Activating RabbitMQ plugins ... 0 plugins activated: node with name "rabbit" already running on "android-d1af002161676bee" diagnostics: - nodes and their ports on android-d1af002161676bee: [{rabbit,52176}, {rabbitmqprelaunch2254, 59205}] - current node: 'rabbitmqprelaunch2254@android-d1af002161676bee' - current node home dir: /Users/Jordan - current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ== But, rabbitmqctl seems to think otherwise: rabbitmqctl -n rabbit status Status of node 'rabbit@android-d1af002161676bee' ... Error: unable to connect to node 'rabbit@android-d1af002161676bee': nodedown diagnostics: - nodes and their ports on android-d1af002161676bee: [{rabbit,52176}, {rabbitmqctl2462,59256}] - current node: 'rabbitmqctl2462@android-d1af002161676bee' - current node home dir: /Users/Jordan - current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ== Any takers?
The rabbitmq server was running somewhere but it just couldn't be connected to. One of the following will mention something about rabbits: $: ps aux | grep epmd $: ps aux | grep erl Kill the process with kill -9 {pid of rabbitmq process}
RabbitMQ
8,737,754
65
I am using rabbitmq:3-management from https://hub.docker.com/_/rabbitmq/ however, it is missing a plugin that I need rabbitmq_delayed_message_exchange. How can I enable this plugin if it is not available in the image?
FROM rabbitmq:3.7-management RUN apt-get update && \ apt-get install -y curl unzip RUN curl https://dl.bintray.com/rabbitmq/community-plugins/3.7.x/rabbitmq_delayed_message_exchange/rabbitmq_delayed_message_exchange-20171201-3.7.x.zip > rabbitmq_delayed_message_exchange-20171201-3.7.x.zip && \ unzip rabbitmq_delayed_message_exchange-20171201-3.7.x.zip && \ rm -f rabbitmq_delayed_message_exchange-20171201-3.7.x.zip && \ mv rabbitmq_delayed_message_exchange-20171201-3.7.x.ez plugins/ RUN rabbitmq-plugins enable rabbitmq_delayed_message_exchange
RabbitMQ
52,819,237
64
I installed RabbitMQ server on OS X, and started it on command line. Now, it is not obvious that how I should stop it from running? After I did: sudo rabbitmq-server -detached I get: Activating RabbitMQ plugins ... 0 plugins activated: That was it. How should I properly shut it down? In the document, it mentions using rabbitmqctl(1), but it's not clear to me what that means. Thanks. Edit: As per comment below, this is what I get for running sudo rabbitmqctl stop: (project_env)mlstr-1:Package mlstr$ sudo rabbitmqctl stop Password: Stopping and halting node rabbit@h002 ... Error: unable to connect to node rabbit@h002: nodedown DIAGNOSTICS =========== nodes in question: [rabbit@h002] hosts, their running nodes and ports: - h002: [{rabbit,62428},{rabbitmqctl7069,64735}] current node details: - node name: rabbitmqctl7069@h002 - home dir: /opt/local/var/lib/rabbitmq - cookie hash: q7VU0JjCd0VG7jOEF9Hf/g== Why is there still a 'current node'? I have not run any client program but only the RabbitMQ server, does that mean a server is still running?
It turns out that it is related to permissions. Somehow my rabbitmq server was started with user 'rabbitmq' (which is strange), so that I had to do sudo -u rabbitmq rabbitmqctl stop
RabbitMQ
10,608,950
64
I'm a newbie with Rabbitmq(and programming) so sorry in advance if this is obvious. I am creating a pool to share between threads that are working on a queue but I'm not sure if I should use connections or channels in the pool. I know I need channels to do the actual work but is there a performance benefit of having one channel per connection(in terms of more throughput from the queue)? or am I better off just using a single connection per application and pool many channels? note: because I'm pooling the resources the initial cost is not a factor, as I know connections are more expensive than channels. I'm more interested in throughput.
I have found this on the rabbitmq website it is near the bottom so I have quoted the relevant part below. The tl;dr version is that you should have 1 connection per application and 1 channel per thread. Connections AMQP connections are typically long-lived. AMQP is an application level protocol that uses TCP for reliable delivery. AMQP connections use authentication and can be protected using TLS (SSL). When an application no longer needs to be connected to an AMQP broker, it should gracefully close the AMQP connection instead of abruptly closing the underlying TCP connection. Channels Some applications need multiple connections to an AMQP broker. However, it is undesirable to keep many TCP connections open at the same time because doing so consumes system resources and makes it more difficult to configure firewalls. AMQP 0-9-1 connections are multiplexed with channels that can be thought of as "lightweight connections that share a single TCP connection". For applications that use multiple threads/processes for processing, it is very common to open a new channel per thread/process and not share channels between them. Communication on a particular channel is completely separate from communication on another channel, therefore every AMQP method also carries a channel number that clients use to figure out which channel the method is for (and thus, which event handler needs to be invoked, for example). It is advised that there is 1 channel per thread, even though they are thread safe, so you could have multiple threads sending through one channel. In terms of your application I would suggest that you stick with 1 channel per thread though. Additionally it is advised to only have 1 consumer per channel. These are only guidelines so you will have to do some testing to see what works best for you. This thread has some insights here and here. Despite all these guidelines this post suggests that it will most likely not affect performance by having multiple connections. Though it is not specific whether it is talking about client side or server(rabbitmq) side. With the one point that it will of course use more systems resources with more connections. If this is not a problem and you wish to have more throughput it may indeed be better to have multiple connections as this post suggests multiple connections will allow you more throughput. The reason seems to be that even if there are multiple channels only one message goes through the connection at one time. Therefore a large message will block the whole connection or many unimportant messages on one channel may block an important message on the same connection but a different channel. Again resources are an issue. If you are using up all the bandwidth with one connection then adding an additional connection will have no increase performance over having two channels on the one connection. Also each connection will use more memory, cpu and filehandles, but that may well not be a concern though might be an issue when scaling.
RabbitMQ
10,407,760
64
I am using RabbitMQ server. For publishing messages, I set the immediate field to true and tried sending 50,000 messages. Using rabbitmqctl list_queues, I saw that the number of messages in the queue was zero. Then, I changed the immediate flag to false and again tried sending 50,000 messages. Using rabbitmqctl list_queues, I saw that a total of 100,000 messages were in queues (till now, no consumer was present). After that, I started a consumer and it consumed all the 100,000 messages. Can anybody please help me in understanding about the immediate bit field and this behavior too? Also, I could not understand the concept of the mandatory bit field.
The immediate and mandatory fields are part of the AMQP specification, and are also covered in the RabbitMQ FAQ to clarify how its implementers interpreted their meaning: Mandatory This flag tells the server how to react if a message cannot be routed to a queue. Specifically, if mandatory is set and after running the bindings the message was placed on zero queues then the message is returned to the sender (with a basic.return). If mandatory had not been set under the same circumstances the server would silently drop the message. Or in my words, "Put this message on at least one queue. If you can't, send it back to me." Immediate For a message published with immediate set, if a matching queue has ready consumers then one of them will have the message routed to it. If the lucky consumer crashes before ack'ing receipt the message will be requeued and/or delivered to other consumers on that queue (if there's no crash the messaged is ack'ed and it's all done as per normal). If, however, a matching queue has zero ready consumers the message will not be enqueued for subsequent redelivery on from that queue. Only if all of the matching queues have no ready consumers that the message is returned to the sender (via basic.return). Or in my words, "If there is at least one consumer connected to my queue that can take delivery of a message right this moment, deliver this message to them immediately. If there are no consumers connected then there's no point in having my message consumed later and they'll never see it. They snooze, they lose."
RabbitMQ
6,386,117
64
Given ReadOnlyMemory Struct I want to convert the stream into a string I have the following code: var body = ea.Body; //ea.Body is of Type ReadOnlyMemory<byte> var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); And it gives the following error. I am using the latest C# with .NET CORE 3.1 Which is funny because I am literally copy pasting the Hello World example of a major product called RabbitMQ and it doesn't compile.
You cannot drop a thing that's read-only into a slot typed as byte[], because byte[]s are writable and that would defeat the purpose. It looks like RabbitMQ changed their API in February and perhaps forgot to update the sample code. A quick workaround is to use .ToArray(): var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); Edit: Since this was accepted, I'll amend it with the better solution posed by Dmitry and zenseb which is to use .Span: var body = ea.Body.Span; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message);
RabbitMQ
61,374,796
62
If my understanding is correct, you can't actually look at messages in the rabbit queue without taking them out and putting them back in. There's no way to use rabbitmqctl to inspect a queue. In some debugging contexts, knowing what is currently in the queue is very useful. Is there a way to get at the messages? Also, what is it about the design of Rabbit that makes this process cumbersome?
There is a "Get Messages" section for each queue in the management API. However this causes the message to be consumed and hence is a destructive action. We can re-queue this message to the queue only at the expense of sacrificing the ordering of messages [for rabbitmq versions < 2.7.0]. A more viable alternative would be to use the firehose tracer, http://www.rabbitmq.com/firehose.html [for rabbitmq versions> 2.5]. This essentially publishes the message to a different exchange (amq.rabbitmq.trace) just for debugging purposes. Here is another GUI written on top of firehose for better visibility, http://www.rabbitmq.com/blog/2011/09/09/rabbitmq-tracing-a-ui-for-the-firehose/
RabbitMQ
9,874,234
62