Springboot+shiro-redis using Redis Sentinel (Sentinel) master-Slave implementation

Source: Internet
Author: User

Recently, the company project encountered a server crash caused the project can not run, because the project uses a single point of Redis to do session sharing, permissions processing, so think of using Redis Master-slave method to reduce the coupling, in order to facilitate later access to the special record here.

Server System for CentOS 7 Redis 4.0.6

Two master-slave redis servers: 192.168.0.35 6379 Master
192.168.0.34 6379 from
One, Redis installation

Cd/opt

Wget http://download.redis.io/releases/redis-4.0.6.tar.gz If you are prompted to locate the command, you need to install: Yum install wget

Tar xzf redis-4.0.6.tar.gz

CD redis-4.0.6
Make

Src/redis-server

Client Access:

Src/redis-cli


Redis Settings boot from:

1. Modify the configuration file parameter Daemonize Yes
. vi/opt/redis-4.0.6/redis.conf

    1. Copy redis configuration file (startup script requires configuration file contents, so copy)
      #1. Create a new Redis folder under/etc
      $ mkdir/etc/redis
      #2. Copy the redis.conf file in the Redis directory to/etc/redis/6379.conf, 6379.conf is the name of the file, and the variables in the startup script will read the name, so if the Redis port number is changed, it should be changed.
      $ cp/opt/redis-4.0.6/redis.conf/etc/redis/6379.conf

      1. Replicating Redis Startup scripts
        Find/-name Redis_init_script
        • Redis startup scripts are generally utils at the Redis root, and if you don't know the path, you can see the path first

      Find/-name Redis_init_script

      • Copy the startup script into the/etc/init.d/redis file
        Cp/opt/redis-3.2.4//utils/redis_init_script/etc/init.d/redis
      • modifying startup script Parameters
        Vi/etc/init.d/redis

Add the following two lines of comment code to the head of the #在/etc/init.d/redis file, which is added below #!/bin/sh in the file

#chkconfig: 2345 10 90
#description: Start and Stop Redis


Also modify the parameters to specify the installation path for Redis

Because of project requirements, Redis requires external access and is password-based:
Masterauth Test (note that setting the password master-slave password is best always, convenient for rear sentinel mode access)

Open Redis Command: Service Redis start
Turn off Redis command: Service Redis stop
Set to boot: Chkconfig Redis on

The Redis installation on this 35 was successful, and the 34 server was installed Similarly, because 34 is from so many configurations in 6379.conf
Slaveof 192.168.0.35 6379


Login 34 View Information

Now the Redis master-slave installation is complete, the following configuration Sentinel

Second, Sentinel Configuration
Edit after #将sentinel配置文件拷贝到/etc/redis directory

1. Auto-start


2. Start
Redis-sentinel sentinel.conf


When the exit is Sentinel also exits, then we use redis-sentinel/etc/redis/sentinel.conf

View process The Sentinel process is always there. The same is also configured on 35 to this redis so the operation ends.

Third, Shior-redis Connect Redis

MAVEN Configuration

It is to be remembered here that the Shiro-redis rack package is used relatively new, when using 2.4.2.1-release, the Sentinel master and slave can not be used.
Application Configuration

Shiroconfig Code

@Configuration
public class Shiroconfig {

  @Value ("${spring.redis.host}") Private String host, @Value ("${spring.redis.port}") private int port; @Value ("${spring.redis.password}") private string password; @Value ("${spring.redis.sentinel.nodes}") private string Redisnodes; @Value ("${spring.redis.sentinel.master}") private String Master; @Value ("${shiro.rediscacheexpire:1800} ") private int rediscacheexpire; @Value (" ${shiro.filterchaindefinitions} ") Private String filterchaindefinitions;@ Value ("${shiro.sessionvalidationinterval:300000}") Private long sessionvalidationinterval; @Autowiredprivate Authorityservice authorityservice;/** * Configure Shiro Redismanager----single point using * Shiro-redis Open Source Plugin * * @return */ 

Public Redismanager Redismanager () {
Redismanager Redismanager = new Redismanager ();
Redismanager.sethost (host);
Redismanager.setport (port);
Redismanager.setpassword (password);
Redismanager.setexpire (Rediscacheexpire);
Redismanager.settimeout (2000);
return redismanager;
// }

/** * 配置shiro redisSentinelManager   哨兵模式 * 使用的是shiro-redis开源插件 * @return */public RedisSentinelManager redisSentinelManager(){    RedisSentinelManager redisSentinelManager = new RedisSentinelManager();    redisSentinelManager.setMasterName(master);    redisSentinelManager.setHost(redisNodes);    redisSentinelManager.setPassword(password);    return redisSentinelManager;}/** * cacheManager 缓存 redis实现 * 使用的是shiro-redis开源插件 * * @return */public RedisCacheManager cacheManager() {    RedisCacheManager redisCacheManager = new RedisCacheManager();

//Rediscachemanager.setredismanager (Redismanager ());
Rediscachemanager.setredismanager (Redissentinelmanager ());
return Rediscachemanager;
}

/** * Redissessiondao Shiro Sessiondao layer is implemented via Redis * using the Shiro-redis open source plugin */public Redissessiondao Redissessiondao () {R    Edissessiondao Redissessiondao = new Redissessiondao ();    Redissessiondao.setredismanager (Redissentinelmanager ()); return Redissessiondao;} /** * Shiro Session Management */public Defaultwebsessionmanager SessionManager () {Defaultwebsessionmanager SessionManager = n    EW Defaultwebsessionmanager ();    Sessionmanager.setsessiondao (Redissessiondao ());    Cookie cookie = Sessionmanager.getsessionidcookie ();    Cookie.setname ("Emp_sid");    Sessionmanager.setsessionidcookie (cookie);    Shiro Session Expiration Listener Sessionmanager.setsessionlisteners (Arrays.aslist (New Shirosessionlistener ()));    Sessionmanager.setsessionvalidationinterval (Sessionvalidationinterval); return SessionManager;} /** * Voucher Match * * @return */public credentialsmatcher credentialsmatcher () {Retrylimithashedcredentialsmatcher Credentia Lsmatcher = new Retrylimithashedcredentialsmatcher (CacheManager ());   Credentialsmatcher.sethashalgorithmname ("MD5");//Cryptographic algorithm name credentialsmatcher.sethashiterations (2);    Credentialsmatcher.setstoredcredentialshexencoded (TRUE); return credentialsmatcher;} /** * Realm Implementation * * @return */@Beanpublic Authorizingrealm Userrealm () {Employeerealm Employeerealm = new Employeerealm (    );    Employeerealm.setcredentialsmatcher (Credentialsmatcher ());    Close login User Information cache employeerealm.setauthenticationcachingenabled (FALSE);    Employeerealm.setauthorizationcachingenabled (TRUE); return Employeerealm;} /** * Security Manager * * @return */@Beanpublic SecurityManager SecurityManager () {Defaultwebsecuritymanager SecurityManager = n    EW Defaultwebsecuritymanager ();    Securitymanager.setrealm (Userrealm ());    Securitymanager.setsessionmanager (SessionManager ());    Securitymanager.setcachemanager (CacheManager ());    Modularrealmauthorizer authorizer = new Modularrealmauthorizer ();    Authorizer.setrealms (Securitymanager.getrealms ()); Authorizer.setpermissionresolver (NewEmployeepermissionresolver ());    Authorizer.setrolepermissionresolver (Rolepermissionresolver ());    Securitymanager.setauthorizer (Authorizer);    Securitymanager.setremembermemanager (Remembermemanager ()); return SecurityManager;} @Beanpublic rolepermissionresolver Rolepermissionresolver () {return new Myrolepermissionresolver ();} @Beanpublic Shirofilterfactorybean shirofilter (SecurityManager securitymanager) {Shirofilterfactorybean    Shirofilterfactorybean = new Shirofilterfactorybean ();    Shirofilterfactorybean.setsecuritymanager (SecurityManager);    map<string, filter> filters = Shirofilterfactorybean.getfilters ();    Staticurlfilter staticurlfilter = new Staticurlfilter ();    Filters.put ("Staticurl", Staticurlfilter);    Tokenfilter tokenfilter=new Tokenfilter ();    Filters.put ("token", tokenfilter);    Authorityfilter authorityfilter = new Authorityfilter ();    Authorityfilter.setactionservice (Authorityservice);    Filters.put ("auth", authorityfilter); Versionfilter Versionfilter = new Versionfilter ();    Filters.put ("version", Versionfilter);    Shirofilterfactorybean.setfilters (filters);    Interceptors.    map<string, string> filterchaindefinitionmap = new linkedhashmap<string, string> (); Configuration will not be blocked by the link sequence judgment//interceptor URL Configuration format:/**=user, the equals sign before the path, followed by the name, multiple interceptors ', ' split, multiple configurations with '; ' Split if (! Stringutils.isempty (filterchaindefinitions)) {string[] array = Stringutils.delimitedlisttostringarray (FilterChainD        Efinitions, ";");            for (String Str:array) {if (Stringutils.isempty (str)) {continue;            } string[] Urlarray = str.split ("="); Filterchaindefinitionmap.put (Urlarray[0].trim (), Urlarray[1].trim ());

string[] Filterarray = Urlarray[1].split (",");
for (String S:filterarray) {
Filterchaindefinitionmap.put (Urlarray[0].trim (), S.trim ());
// }
}
}
Shirofilterfactorybean.setfilterchaindefinitionmap (FILTERCHAINDEFINITIONMAP);
Shirofilterfactorybean.setfilterchaindefinitions (filterchaindefinitions);
If you do not set the default will automatically look for the "/login.jsp" page under the Web project root directory
Shirofilterfactorybean.setloginurl ("/login");
Link to jump after successful login
Shirofilterfactorybean.setsuccessurl ("/");
Shirofilterfactorybean.setunauthorizedurl ("/401");

    return shiroFilterFactoryBean;}public CookieRememberMeManager rememberMeManager() {    CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();    rememberMeManager.getCookie().setMaxAge(2592000);//有效期30天    rememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));    return rememberMeManager;}

}

Springboot+shiro-redis using Redis Sentinel (Sentinel) master-Slave implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.