https://download.redis.io/releases/ 사용하려는 레디스 버전을 확인 후 다운로드
wget https://download.redis.io/releases/redis-3.0.7.tar.gz
tar xzf redis-3.0.7.tar.gz
make
make install PREFIX=/usr/local/redis
or
yum install redis-3.0.7
redis.conf 설정 (https://redis.io/docs/latest/operate/oss_and_stack/management/config/)
- The self-documented redis.conf for Redis 3.0. 을 참고해서 필요한 옵션을 설정
# Redis configuration file example.
#
# Note that in order to read the configuration file, Redis must be
# started with the file path as first argument:
#
# ./redis-server /path/to/redis.conf
# Note on units: when memory size is needed, it is possible to specify
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.
################################## INCLUDES ###################################
# Include one or more other config files here. This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings. Include files can include
# other files, so use this wisely.
#
# Notice option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include /path/to/local.conf
# include /path/to/other.conf
################################ GENERAL #####################################
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no
# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
# default. You can specify a custom pid file location here.
pidfile /var/run/redis.pid
# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
```
sentinel.conf 설정 ( High availability with Redis Sentinel | Docs)
# Example sentinel.conf
# By default protected mode is disabled in sentinel mode. Sentinel is reachable
# from interfaces different than localhost. Make sure the sentinel instance is
# protected from the outside world via firewalling or other means.
protected-mode no
# port <sentinel-port>
# The port that this sentinel instance will run on
port 26379
# By default Redis Sentinel does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis-sentinel.pid when
# daemonized.
daemonize no
# When running daemonized, Redis Sentinel writes a pid file in
# /var/run/redis-sentinel.pid by default. You can specify a custom pid file
# location here.
pidfile /var/run/redis-sentinel.pid
# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
# nothing (nothing is logged)
loglevel notice
# Specify the log file name. Also the empty string can be used to force
# Sentinel to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile ""
# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no
# Specify the syslog identity.
# syslog-ident sentinel
# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0
# sentinel announce-ip <ip>
# sentinel announce-port <port>
#
# The above two configuration directives are useful in environments where,
# because of NAT, Sentinel is reachable from outside via a non-local address.
#
# When announce-ip is provided, the Sentinel will claim the specified IP address
# in HELLO messages used to gossip its presence, instead of auto-detecting the
# local address as it usually does.
#
# Similarly when announce-port is provided and is valid and non-zero, Sentinel
# will announce the specified TCP port.
#
# The two options don't need to be used together, if only announce-ip is
# provided, the Sentinel will announce the specified IP and the server port
# as specified by the "port" option. If only announce-port is provided, the
# Sentinel will announce the auto-detected local IP and the specified port.
#
# Example:
#
# sentinel announce-ip 1.2.3.4
# dir <working-directory>
# Every long running process should have a well-defined working directory.
# For Redis Sentinel to chdir to /tmp at startup is the simplest thing
# for the process to don't interfere with administrative tasks such as
# unmounting filesystems.
dir /tmp
# sentinel monitor <master-name> <ip> <redis-port> <quorum>
#
# Tells Sentinel to monitor this master, and to consider it in O_DOWN
# (Objectively Down) state only if at least <quorum> sentinels agree.
#
# Note that whatever is the ODOWN quorum, a Sentinel will require to
# be elected by the majority of the known Sentinels in order to
# start a failover, so no failover can be performed in minority.
#
# Replicas are auto-discovered, so you don't need to specify replicas in
# any way. Sentinel itself will rewrite this configuration file adding
# the replicas using additional configuration options.
# Also note that the configuration file is rewritten when a
# replica is promoted to master.
#
# Note: master name should not include special characters or spaces.
# The valid charset is A-z 0-9 and the three characters ".-_".
sentinel monitor mymaster 127.0.0.1 6379 2
# sentinel auth-pass <master-name> <password>
#
# Set the password to use to authenticate with the master and replicas.
# Useful if there is a password set in the Redis instances to monitor.
#
# Note that the master password is also used for replicas, so it is not
# possible to set a different password in masters and replicas instances
# if you want to be able to monitor these instances with Sentinel.
#
# However you can have Redis instances without the authentication enabled
# mixed with Redis instances requiring the authentication (as long as the
# password set is the same for all the instances requiring the password) as
# the AUTH command will have no effect in Redis instances with authentication
# switched off.
#
# Example:
#
# sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
# sentinel auth-user <master-name> <username>
#
# This is useful in order to authenticate to instances having ACL capabilities,
# that is, running Redis 6.0 or greater. When just auth-pass is provided the
# Sentinel instance will authenticate to Redis using the old "AUTH <pass>"
# method. When also an username is provided, it will use "AUTH <user> <pass>".
# In the Redis servers side, the ACL to provide just minimal access to
# Sentinel instances, should be configured along the following lines:
#
# user sentinel-user >somepassword +client +subscribe +publish \
# +ping +info +multi +slaveof +config +client +exec on
# sentinel down-after-milliseconds <master-name> <milliseconds>
#
# Number of milliseconds the master (or any attached replica or sentinel) should
# be unreachable (as in, not acceptable reply to PING, continuously, for the
# specified period) in order to consider it in S_DOWN state (Subjectively
# Down).
#
# Default is 30 seconds.
sentinel down-after-milliseconds mymaster 30000
# IMPORTANT NOTE: starting with Redis 6.2 ACL capability is supported for
# Sentinel mode, please refer to the Redis website https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
# for more details.
# Sentinel's ACL users are defined in the following format:
#
# user <username> ... acl rules ...
#
# For example:
#
# user worker +@admin +@connection ~* on >ffa9203c493aa99
#
# For more information about ACL configuration please refer to the Redis
# website at https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/ and redis server configuration
# template redis.conf.
# ACL LOG
#
# The ACL Log tracks failed commands and authentication events associated
# with ACLs. The ACL Log is useful to troubleshoot failed commands blocked
# by ACLs. The ACL Log is stored in memory. You can reclaim memory with
# ACL LOG RESET. Define the maximum entry length of the ACL Log below.
acllog-max-len 128
# Using an external ACL file
#
# Instead of configuring users here in this file, it is possible to use
# a stand-alone file just listing users. The two methods cannot be mixed:
# if you configure users here and at the same time you activate the external
# ACL file, the server will refuse to start.
#
# The format of the external ACL user file is exactly the same as the
# format that is used inside redis.conf to describe users.
#
# aclfile /etc/redis/sentinel-users.acl
# requirepass <password>
#
# You can configure Sentinel itself to require a password, however when doing
# so Sentinel will try to authenticate with the same password to all the
# other Sentinels. So you need to configure all your Sentinels in a given
# group with the same "requirepass" password. Check the following documentation
# for more info: https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/
#
# IMPORTANT NOTE: starting with Redis 6.2 "requirepass" is a compatibility
# layer on top of the ACL system. The option effect will be just setting
# the password for the default user. Clients will still authenticate using
# AUTH <password> as usually, or more explicitly with AUTH default <password>
# if they follow the new protocol: both will work.
#
# New config files are advised to use separate authentication control for
# incoming connections (via ACL), and for outgoing connections (via
# sentinel-user and sentinel-pass)
#
# The requirepass is not compatible with aclfile option and the ACL LOAD
# command, these will cause requirepass to be ignored.
# sentinel sentinel-user <username>
#
# You can configure Sentinel to authenticate with other Sentinels with specific
# user name.
# sentinel sentinel-pass <password>
#
# The password for Sentinel to authenticate with other Sentinels. If sentinel-user
# is not configured, Sentinel will use 'default' user with sentinel-pass to authenticate.
# sentinel parallel-syncs <master-name> <numreplicas>
#
# How many replicas we can reconfigure to point to the new replica simultaneously
# during the failover. Use a low number if you use the replicas to serve query
# to avoid that all the replicas will be unreachable at about the same
# time while performing the synchronization with the master.
sentinel parallel-syncs mymaster 1
# sentinel failover-timeout <master-name> <milliseconds>
#
# Specifies the failover timeout in milliseconds. It is used in many ways:
#
# - The time needed to re-start a failover after a previous failover was
# already tried against the same master by a given Sentinel, is two
# times the failover timeout.
#
# - The time needed for a replica replicating to a wrong master according
# to a Sentinel current configuration, to be forced to replicate
# with the right master, is exactly the failover timeout (counting since
# the moment a Sentinel detected the misconfiguration).
#
# - The time needed to cancel a failover that is already in progress but
# did not produced any configuration change (SLAVEOF NO ONE yet not
# acknowledged by the promoted replica).
#
# - The maximum time a failover in progress waits for all the replicas to be
# reconfigured as replicas of the new master. However even after this time
# the replicas will be reconfigured by the Sentinels anyway, but not with
# the exact parallel-syncs progression as specified.
#
# Default is 3 minutes.
sentinel failover-timeout mymaster 180000
# SCRIPTS EXECUTION
#
# sentinel notification-script and sentinel reconfig-script are used in order
# to configure scripts that are called to notify the system administrator
# or to reconfigure clients after a failover. The scripts are executed
# with the following rules for error handling:
#
# If script exits with "1" the execution is retried later (up to a maximum
# number of times currently set to 10).
#
# If script exits with "2" (or an higher value) the script execution is
# not retried.
#
# If script terminates because it receives a signal the behavior is the same
# as exit code 1.
#
# A script has a maximum running time of 60 seconds. After this limit is
# reached the script is terminated with a SIGKILL and the execution retried.
# NOTIFICATION SCRIPT
#
# sentinel notification-script <master-name> <script-path>
#
# Call the specified notification script for any sentinel event that is
# generated in the WARNING level (for instance -sdown, -odown, and so forth).
# This script should notify the system administrator via email, SMS, or any
# other messaging system, that there is something wrong with the monitored
# Redis systems.
#
# The script is called with just two arguments: the first is the event type
# and the second the event description.
#
# The script must exist and be executable in order for sentinel to start if
# this option is provided.
#
# Example:
#
# sentinel notification-script mymaster /var/redis/notify.sh
# CLIENTS RECONFIGURATION SCRIPT
#
# sentinel client-reconfig-script <master-name> <script-path>
#
# When the master changed because of a failover a script can be called in
# order to perform application-specific tasks to notify the clients that the
# configuration has changed and the master is at a different address.
#
# The following arguments are passed to the script:
#
# <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
#
# <state> is currently always "start"
# <role> is either "leader" or "observer"
#
# The arguments from-ip, from-port, to-ip, to-port are used to communicate
# the old address of the master and the new address of the elected replica
# (now a master).
#
# This script should be resistant to multiple invocations.
#
# Example:
#
# sentinel client-reconfig-script mymaster /var/redis/reconfig.sh
# SECURITY
#
# By default SENTINEL SET will not be able to change the notification-script
# and client-reconfig-script at runtime. This avoids a trivial security issue
# where clients can set the script to anything and trigger a failover in order
# to get the program executed.
sentinel deny-scripts-reconfig yes
# REDIS COMMANDS RENAMING (DEPRECATED)
#
# WARNING: avoid using this option if possible, instead use ACLs.
#
# Sometimes the Redis server has certain commands, that are needed for Sentinel
# to work correctly, renamed to unguessable strings. This is often the case
# of CONFIG and SLAVEOF in the context of providers that provide Redis as
# a service, and don't want the customers to reconfigure the instances outside
# of the administration console.
#
# In such case it is possible to tell Sentinel to use different command names
# instead of the normal ones. For example if the master "mymaster", and the
# associated replicas, have "CONFIG" all renamed to "GUESSME", I could use:
#
# SENTINEL rename-command mymaster CONFIG GUESSME
#
# After such configuration is set, every time Sentinel would use CONFIG it will
# use GUESSME instead. Note that there is no actual need to respect the command
# case, so writing "config guessme" is the same in the example above.
#
# SENTINEL SET can also be used in order to perform this configuration at runtime.
#
# In order to set a command back to its original name (undo the renaming), it
# is possible to just rename a command to itself:
#
# SENTINEL rename-command mymaster CONFIG CONFIG
# HOSTNAMES SUPPORT
#
# Normally Sentinel uses only IP addresses and requires SENTINEL MONITOR
# to specify an IP address. Also, it requires the Redis replica-announce-ip
# keyword to specify only IP addresses.
#
# You may enable hostnames support by enabling resolve-hostnames. Note
# that you must make sure your DNS is configured properly and that DNS
# resolution does not introduce very long delays.
#
SENTINEL resolve-hostnames no
# When resolve-hostnames is enabled, Sentinel still uses IP addresses
# when exposing instances to users, configuration files, etc. If you want
# to retain the hostnames when announced, enable announce-hostnames below.
#
SENTINEL announce-hostnames no
# When master_reboot_down_after_period is set to 0, Sentinel does not fail over
# when receiving a -LOADING response from a master. This was the only supported
# behavior before version 7.0.
#
# Otherwise, Sentinel will use this value as the time (in ms) it is willing to
# accept a -LOADING response after a master has been rebooted, before failing
# over.
SENTINEL master-reboot-down-after-period mymaster 0
failover 시 slave 노드를 master 노드로 승격시키기 위해 설정된 정족수(quorum) 이상 개수의 동의가 필요한데 그에 맞는 sentinel을 여러 개 구성해야 한다. 최소 quorum은 2개이상, sentinel 3개 이상이어야 안정된 서비스가 보장된다.
처음 모든 sentinel.conf 설정 시 mymaster는 현재 role이 마스터인 노드의 정보만을 입력한다.
sentinel 사용 시 필요한 포트의 방화벽은 열어두어야 한다.
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port protocol="tcp" port="26379" accept'
firewall-cmd --reload
firewall-cmd --list-rich-rules
redis-cli -a password info를 통해 연결된 정보를 확인
# Replication
role:master
connected_slaves:2
slave0:ip=node1,port=6379,state=online,offset=13633266,lag=0
slave1:ip=node2,port=6379,state=online,offset=13633266,lag=1
sentinel.conf sentinel이 자동으로 작성한 정보 확인
# Generated by CONFIG REWRITE
sentinel leader-epoch mymaster 255
sentinel known-slave mymaster node1 6379
sentinel known-slave mymaster node2 6379
sentinel known-sentinel mymaster node1 26379 uid1
sentinel known-sentinel mymaster node2 26379 uid2
sentinel current-epoch 255
failover sentinel 로그
14698:X 21 Oct 12:10:42.132 # +sdown master mymaster node1 6379
14698:X 21 Oct 12:10:42.223 # +odown master mymaster node1 6379 #quorum 2/2
14698:X 21 Oct 12:10:42.223 # +new-epoch 256
14698:X 21 Oct 12:10:42.223 # +try-failover master mymaster node1 6379
14698:X 21 Oct 12:10:42.224 # +vote-for-leader node1Uid 256
14698:X 21 Oct 12:10:42.272 # node2Uid voted for node1Uid 256
14698:X 21 Oct 12:10:42.280 # +elected-leader master mymaster node1 6379
14698:X 21 Oct 12:10:42.280 # +failover-state-select-slave master mymaster node1 6379
14698:X 21 Oct 12:10:42.352 # +selected-slave slave node2:6379 node2 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:42.352 * +failover-state-send-slaveof-noone slave node2:6379 node2 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:42.390 # node3Uid voted for node1Uid 256
14698:X 21 Oct 12:10:42.435 * +failover-state-wait-promotion slave node2:6379 node2 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:43.135 # +promoted-slave slave node2:6379 node2 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:43.135 # +failover-state-reconf-slaves master mymaster node1 6379
14698:X 21 Oct 12:10:43.206 * +slave-reconf-sent slave node3:6379 node3 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:43.273 * +slave-reconf-inprog slave node3:6379 node3 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:43.466 # -odown master mymaster node1 6379
14698:X 21 Oct 12:10:49.253 # +new-epoch 257
14698:X 21 Oct 12:10:53.146 # +failover-end-for-timeout master mymaster node1 6379
14698:X 21 Oct 12:10:53.146 # +failover-end master mymaster node1 6379
14698:X 21 Oct 12:10:53.146 * +slave-reconf-sent-be slave node3:6379 node3 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:53.146 * +slave-reconf-sent-be slave node2:6379 node2 6379 @ mymaster node1 6379
14698:X 21 Oct 12:10:53.146 # +switch-master mymaster node1 6379 node2 6379
14698:X 21 Oct 12:10:53.147 * +slave slave node3:6379 node3 6379 @ mymaster node2 6379
14698:X 21 Oct 12:10:53.147 * +slave slave node1:6379 node1 6379 @ mymaster node2 6379
14698:X 21 Oct 12:10:58.182 # +sdown slave node1:6379 node1 6379 @ mymaster node2 6379
로그 파일이 하나로 append되기 때문에 logrotate로 일자별 분리
sentinel.conf, redis.conf 설정에서 pidfile "/var/run/sentinel.pid" 위치를 지정하는 편이 편함
sudo vi /etc/logrotate.d/redis-sentinel
# redis-sentinel content
/var/log/redis/sentinel.log {
daily
rotate 14
missingok
notifempty
compress
delaycompress
dateext
dateformat -%Y-%m-%d
sharedscripts
postrotate
# Sentinel PID 파일 위치 확인 필요
if [ -f /var/run/redis/sentinel.pid ]; then
kill -HUP $(cat /var/run/redis/sentinel.pid)
else
kill -HUP $(pidof redis-sentinel)
fi
endscript
}
sudo logrotate -f /etc/logrotate.d/redis-sentinel
Spring 4.0.5 기준 CacheErrorHandler(since 4.1)가 없기 때문에 직접 예외처리, circuitBreaker같은 기능도 추가
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCache;
public class SafeRedisCache implements Cache {
private final static Logger logger = LoggerFactory.getLogger(SafeRedisCache.class);
private final RedisCache delegate;
private final int failureThreshold;
private final long openStateDurationMillis;
private final AtomicInteger failureCount = new AtomicInteger(0);
private volatile long lastFailureTime = 0L;
private volatile boolean circuitState = false;
public SafeRedisCache(RedisCache delegate) {
this(delegate, 5, 60000L);
}
public SafeRedisCache(RedisCache delegate, int failureThreshold, long openStateDurationMillis) {
this.delegate = delegate;
this.failureThreshold = failureThreshold;
this.openStateDurationMillis = openStateDurationMillis;
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public Object getNativeCache() {
return delegate.getNativeCache();
}
@Override
public ValueWrapper get(Object key) {
if (isOpenCircuit()) {
return null;
}
try {
ValueWrapper valueWrapper = delegate.get(key);
onSuccess();
return valueWrapper;
} catch (RuntimeException e) {
onFailure(e);
return null;
}
}
@Override
public <T> T get(Object key, Class<T> type) {
if (isOpenCircuit()) {
return null;
}
try {
T value = (T) delegate.get(key);
onSuccess();
return value;
} catch (RuntimeException e) {
onFailure(e);
return null;
}
}
@Override
public void put(Object key, Object value) {
if (isOpenCircuit()) {
return;
}
try {
delegate.put(key, value);
onSuccess();
} catch (RuntimeException e) {
onFailure(e);
}
}
@Override
public void evict(Object key) {
if (isOpenCircuit()) {
return;
}
try {
delegate.evict(key);
onSuccess();
} catch (RuntimeException e) {
onFailure(e);
}
}
@Override
public void clear() {
if (isOpenCircuit()) {
return;
}
try {
delegate.clear();
onSuccess();
} catch (RuntimeException e) {
onFailure(e);
}
}
private void onFailure(RuntimeException e) {
int failures = failureCount.incrementAndGet();
if (!circuitState && failures >= failureThreshold) {
openCircuit();
}
}
private void onSuccess() {
circuitState = false;
failureCount.set(0);
}
private void openCircuit() {
circuitState = true;
lastFailureTime = System.currentTimeMillis();
}
private boolean isOpenCircuit() {
if (circuitState) {
long now = System.currentTimeMillis();
if (now - lastFailureTime >= openStateDurationMillis) {
circuitState = false;
return false;
}
return true;
}
return false;
}
}
cache value별로 expire을 관리할 수 있다. setUsePrefix를 사용해야 @Cacheable(value = "")로 등록한 값이 key값 앞에 자동으로 붙는다.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.DefaultRedisCachePrefix;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
public class SafeRedisCacheManager implements CacheManager {
private final RedisCacheManager delegate;
public SafeRedisCacheManager(RedisTemplate redisTemplate, DefaultRedisCachePrefix defaultRedisCachePrefix) {
this.delegate = new RedisCacheManager(redisTemplate);
delegate.setUsePrefix(true);
delegate.setCachePrefix(defaultRedisCachePrefix);
delegate.setDefaultExpiration(3600L);
Map<String, Long> expires = new HashMap<String, Long>();
expires.put("code", 3600L);
expires.put("leftMenu", 86400L);
expires.put("topMenu", 86400L);
delegate.setExpires(expires);
}
@Override
public Cache getCache(String name) {
Cache original = delegate.getCache(name);
if (original instanceof RedisCache) {
return new SafeRedisCache((RedisCache) original);
}
return original;
}
@Override
public Collection<String> getCacheNames() {
return delegate.getCacheNames();
}
}
Redis cache 사용하도록 spring 빈 등록
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
```
<cache:annotation-driven cache-manager="cacheManager"/>
<beans:bean id="masterNode" class="org.springframework.data.redis.connection.RedisNode">
<beans:property name="name" value="mymaster"/>
</beans:bean>
<beans:bean id="redisSentinelConfig" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<beans:property name="master" ref="masterNode"/>
<beans:property name="sentinels">
<beans:set>
<beans:bean class="org.springframework.data.redis.connection.RedisNode">
<beans:constructor-arg value="node1-ip"/>
<beans:constructor-arg value="26379"/>
</beans:bean>
<beans:bean class="org.springframework.data.redis.connection.RedisNode">
<beans:constructor-arg value="node2-ip"/>
<beans:constructor-arg value="26379"/>
</beans:bean>
<beans:bean class="org.springframework.data.redis.connection.RedisNode">
<beans:constructor-arg value="node3-ip"/>
<beans:constructor-arg value="26379"/>
</beans:bean>
</beans:set>
</beans:property>
</beans:bean>
<beans:bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<beans:constructor-arg type="org.springframework.data.redis.connection.RedisSentinelConfiguration" ref="redisSentinelConfig"/>
<beans:property name="password" value="password"/>
<beans:property name="usePool" value="true"/>
<beans:property name="timeout" value="100"/>
</beans:bean>
<beans:bean id="jacksonSerializer" class="com.mypackage.JacksonJsonRedisSerializer"/>
<beans:bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<beans:property name="connectionFactory" ref="redisConnectionFactory"/>
<beans:property name="keySerializer">
<beans:bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</beans:property>
<beans:property name="hashKeySerializer">
<beans:bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</beans:property>
<beans:property name="valueSerializer" ref="jacksonSerializer"/>
<beans:property name="hashValueSerializer" ref="jacksonSerializer"/>
</beans:bean>
<beans:bean id="redisCachePrefix" class="org.springframework.data.redis.cache.DefaultRedisCachePrefix"/>
<beans:bean id="cacheManager" class="com.mypackage.SafeRedisCacheManager">
<beans:constructor-arg ref="redisTemplate"/>
<beans:constructor-arg ref="redisCachePrefix"/>
</beans:bean>
'Spring' 카테고리의 다른 글
| Transaction rolled back because it has been marked as rollback-only (0) | 2024.07.24 |
|---|---|
| Spring cache abstraction(spring framework 6.1.4) (0) | 2024.02.16 |
| tomcat 사용해서 war 배포 시 외부 업로드 폴더 지정 (0) | 2023.12.15 |
| Spring UncategorizedSQLException(Spring Framework 6.0.10 API) (0) | 2023.07.07 |
| 패키지 경로에 따른 Datasource 설정 (0) | 2023.01.06 |
