2011-05-08 11 views
30

He intentado agregar en el camino -l 11211 -l 11212 en el archivo conf memcached. Pero es sólo escuchando primero es decir 1121¿Cómo podemos crear dos instancias de servidor memcached en el mismo servidor en un puerto diferente?

+0

Para la simulación del entorno de clúster, ejecuto dos tomcat en un servidor, pero ambos servidores están compartiendo un servidor mysql. Por favor, corríjame si estoy equivocado. Para el propósito de compartir una sesión fija, necesito ejecutar el comando memcahed como daemon. – panalbish

Respuesta

43

Esto es lo MemCached dice el comando -l es para:

-l <addr>  interface to listen on (default: INADDR_ANY, all addresses) 
       <addr> may be specified as host:port. If you don't specify 
       a port number, the value you specified with -p or -U is 
       used. You may specify multiple addresses separated by comma 
       or by using -l multiple times 

En primer lugar se necesita especificar la interfaz que desea memcached para que escuche en si está utilizando el -l bandera. Use 0.0.0.0 para todas las interfaces y use 127.0.0.1 si solo desea poder acceder a memcached desde localhost. Segundo, no use dos banderas -l. Use solo uno y separe cada dirección con una coma. El siguiente comando debe hacer lo que quieras.

memcached -l 0.0.0.0:11211,0.0.0.0:11212 

Tenga en cuenta que esto tendrá una instancia de memcached para escuchar en dos puertos. Para tener dos instancias de memcached en una máquina, ejecute estos dos comandos.

memcached -p 11211 -d 

memcached -p 11212 -d 
+0

Gracias por la respuesta. Trabajando como encanto :) – panalbish

+0

Wow gracias, esto realmente me va a ayudar con mi clúster. – WojonsTech

+0

ninguno de estos funciona para mí en 1.4.2 y la documentación a la que se hace referencia ya no parece existir. – Brunis

60

Primero usé la solución de mikewied, pero luego me topé con el problema de iniciar automáticamente el daemon. Otra cosa confusa en esa solución es que no usa la configuración de etc. Estaba a punto de crear mis propios scripts de inicio en /etc/init.d pero luego busqué en el archivo /etc/init.d/memcached y vi este hermoso solución

# Usage: 
# cp /etc/memcached.conf /etc/memcached_server1.conf 
# cp /etc/memcached.conf /etc/memcached_server2.conf 
# start all instances: 
# /etc/init.d/memcached start 
# start one instance: 
# /etc/init.d/memcached start server1 
# stop all instances: 
# /etc/init.d/memcached stop 
# stop one instance: 
# /etc/init.d/memcached stop server1 
# There is no "status" command. 

Básicamente lectores de esta pregunta sólo tiene que leer el archivo /etc/init.d/memcached.

Saludos

+7

Esta debería ser la solución elegida – Avision

+0

Creo que su script de inicio debe ser diferente. En CenOS 6, leí el archivo /etc/init.d/memcached y no veo cómo funcionarían los comandos enumerados sin modificarlo. Tal vez soy lento :) – im3r3k

+1

Tenga en cuenta que esto no funciona para Debain Jessie debido a este error: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=784357. Hay soluciones en el ticket. – gArn

0

en /etc/memcached.conf sólo se puede editar como a continuación

-l 192.168.112.22,127.0.0.1

debe utilizar coma entre dos direcciones IP

2

La respuesta de David Dzhagayev es la mejor. Si no tiene la versión correcta de la secuencia de comandos de inicio Memcache, aquí está la que está hablando:

Debería funcionar con cualquier distribución de Linux utilizando init.

#! /bin/bash 
### BEGIN INIT INFO 
# Provides:   memcached 
# Required-Start:  $remote_fs $syslog 
# Required-Stop:  $remote_fs $syslog 
# Should-Start:    $local_fs 
# Should-Stop:   $local_fs 
# Default-Start:  2 3 4 5 
# Default-Stop:    0 1 6 
# Short-Description: Start memcached daemon 
# Description:   Start up memcached, a high-performance memory caching daemon 
### END INIT INFO 

# Usage: 
# cp /etc/memcached.conf /etc/memcached_server1.conf 
# cp /etc/memcached.conf /etc/memcached_server2.conf 
# start all instances: 
# /etc/init.d/memcached start 
# start one instance: 
# /etc/init.d/memcached start server1 
# stop all instances: 
# /etc/init.d/memcached stop 
# stop one instance: 
# /etc/init.d/memcached stop server1 
# There is no "status" command. 

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin 
DAEMON=/usr/bin/memcached 
DAEMONNAME=memcached 
DAEMONBOOTSTRAP=/usr/share/memcached/scripts/start-memcached 
DESC=memcached 

test -x $DAEMON || exit 0 
test -x $DAEMONBOOTSTRAP || exit 0 

set -e 

. /lib/lsb/init-functions 

# Edit /etc/default/memcached to change this. 
ENABLE_MEMCACHED=no 
test -r /etc/default/memcached && . /etc/default/memcached 


FILES=(/etc/memcached_*.conf) 
# check for alternative config schema 
if [ -r "${FILES[0]}" ]; then 
    CONFIGS=() 
    for FILE in "${FILES[@]}"; 
    do 
    # remove prefix 
    NAME=${FILE#/etc/} 
    # remove suffix 
    NAME=${NAME%.conf} 

    # check optional second param 
    if [ $# -ne 2 ]; 
    then 
     # add to config array 
     CONFIGS+=($NAME) 
    elif [ "memcached_$2" == "$NAME" ]; 
    then 
     # use only one memcached 
     CONFIGS=($NAME) 
     break; 
    fi; 
    done; 

    if [ ${#CONFIGS[@]} == 0 ]; 
    then 
    echo "Config not exist for: $2" >&2 
    exit 1 
    fi; 
else 
    CONFIGS=(memcached) 
fi; 

CONFIG_NUM=${#CONFIGS[@]} 
for ((i=0; i < $CONFIG_NUM; i++)); do 
    NAME=${CONFIGS[${i}]} 
    PIDFILE="/var/run/${NAME}.pid" 

case "$1" in 
    start) 
     echo -n "Starting $DESC: " 
     if [ $ENABLE_MEMCACHED = yes ]; then 
      start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- /etc/${NAME}.conf $PIDFILE 
      echo "$NAME." 
     else 
      echo "$NAME disabled in /etc/default/memcached." 
     fi 
     ;; 
    stop) 
     echo -n "Stopping $DESC: " 
     start-stop-daemon --stop --quiet --oknodo --retry 5 --pidfile $PIDFILE --exec $DAEMON 
     echo "$NAME." 
     rm -f $PIDFILE 
     ;; 

    restart|force-reload) 
     # 
     #  If the "reload" option is implemented, move the "force-reload" 
     #  option to the "reload" entry above. If not, "force-reload" is 
     #  just the same as "restart". 
     # 
     echo -n "Restarting $DESC: " 
     start-stop-daemon --stop --quiet --oknodo --retry 5 --pidfile $PIDFILE 
     rm -f $PIDFILE 
     if [ $ENABLE_MEMCACHED = yes ]; then 
       start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- /etc/${NAME}.conf $PIDFILE 
       echo "$NAME." 
     else 
      echo "$NAME disabled in /etc/default/memcached." 
     fi 
     ;; 
    status) 
     status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $? 
     ;; 
    *) 
     N=/etc/init.d/$NAME 
     echo "Usage: $N {start|stop|restart|force-reload|status}" >&2 
     exit 1 
     ;; 
esac 
done; 

exit 0 
0

Bien, muy buena respuesta, Tristan CHARBONNIER. favor reemplace el código en el archivo/usr/share/memcached/scripts/start-memcached:

#!/usr/bin/perl -w 
# start-memcached 
# 2003/2004 - Jay Bonci 
# This script handles the parsing of the /etc/memcached.conf file 
# and was originally created for the Debian distribution. 
# Anyone may use this little script under the same terms as 
# memcached itself. 

use strict; 

if($> != 0 and $< != 0) 
{ 
    print STDERR "Only root wants to run start-memcached.\n"; 
    exit; 
} 

my $params; my $etchandle; my $etcfile = "/etc/memcached.conf"; 

# This script assumes that memcached is located at /usr/bin/memcached, and 
# that the pidfile is writable at /var/run/memcached.pid 

my $memcached = "/usr/bin/memcached"; 
my $pidfile = "/var/run/memcached.pid"; 

if (scalar(@ARGV) == 2) { 
    $etcfile = shift(@ARGV); 
    $pidfile = shift(@ARGV); 
} 

# If we don't get a valid logfile parameter in the /etc/memcached.conf file, 
# we'll just throw away all of our in-daemon output. We need to re-tie it so 
# that non-bash shells will not hang on logout. Thanks to Michael Renner for 
# the tip 
my $fd_reopened = "/dev/null"; 

    sub handle_logfile 
    { 
     my ($logfile) = @_; 
     $fd_reopened = $logfile; 
    } 

    sub reopen_logfile 
    { 
     my ($logfile) = @_; 

     open *STDERR, ">>$logfile"; 
     open *STDOUT, ">>$logfile"; 
     open *STDIN, ">>/dev/null"; 
     $fd_reopened = $logfile; 
    } 

# This is set up in place here to support other non -[a-z] directives 

my $conf_directives = { 
    "logfile" => \&handle_logfile, 
}; 

if(open $etchandle, $etcfile) 
{ 
    foreach my $line (< $etchandle>) 
    { 
     $line ||= ""; 
     $line =~ s/\#.*//g; 
     $line =~ s/\s+$//g; 
     $line =~ s/^\s+//g; 
     next unless $line; 
     next if $line =~ /^\-[dh]/; 

     if($line =~ /^[^\-]/) 
     { 
      my ($directive, $arg) = $line =~ /^(.*?)\s+(.*)/; 
      $conf_directives->{$directive}->($arg); 
      next; 
     } 

     push @$params, $line;  
    } 

}else{ 
    $params = []; 
} 

    push @$params, "-u root" unless(grep "-u", @$params); 
    $params = join " ", @$params; 

if(-e $pidfile) 
{ 
    open PIDHANDLE, "$pidfile"; 
    my $localpid = <PIDHANDLE>; 
    close PIDHANDLE; 

    chomp $localpid; 
    if(-d "/proc/$localpid") 
    { 
     print STDERR "memcached is already running.\n"; 
     exit;  
    }else{ 
     `rm -f $localpid`; 
    } 

} 

my $pid = fork(); 

if($pid == 0) 
{ 
     reopen_logfile($fd_reopened); 
     exec "$memcached $params"; 
     exit(0); 

}else{ 
    if(open PIDHANDLE,">$pidfile") 
    { 
     print PIDHANDLE $pid; 
     close PIDHANDLE; 
    }else{ 

     print STDERR "Can't write pidfile to $pidfile.\n"; 
    } 
} 
1

solución simple a Centos 6

primera copia /etc/sysconfig/memcached a /etc/sysconfig/memcached2 y escribir nuevos valores para el nuevo archivo .

luego copiar /etc/init.d/memcached a /etc/init.d/memcached2 y el cambio en el nuevo archivo:

  • PORT a su nuevo puerto (hay que restablecer desde /etc/sysconfig/memcached2, por lo que lo hace por si acaso)
  • /etc/sysconfig/memcached a /etc/sysconfig/memcached2
  • /var/run/memcached/memcached.pid-/var/run/memcached/memcached2.pid
  • /var/lock/subsys/memcached-/var/lock/subsys/memcached2

Ahora puede usar service memcached2 start, service memcached2 stop etc. No olvide que chkconfig memcached2 está activo para ejecutarlo cuando la máquina se inicie.

0

En caso de que alguien más tropiece con esta pregunta, hay un error en la distribución debian de memcached (lo que significa que los sabores como Ubuntu también se verían afectados).

https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=784357

Debido a este error, incluso cuando tiene archivos de configuración separados, cuando se ejecuta sudo service memcached restart, sólo el archivo de configuración por defecto en /etc/memcached.conf se cargará.

Como se mencionó en la comment here, la solución temporal es

  1. Retire /lib/systemd/system/memcached.service

  2. Run sudo systemctl daemon-reload (no se preocupe, es seguro hacerlo así )

  3. Finalmente, ejecute sudo service memcached reload

Cuestiones relacionadas