Spring Boot using Redis achieve shared session

Source - plain text house blog: https://blog.yoodb.com/yoodb/article/detail/1421
Redis is a cache messaging middleware and key-value storage systems feature-rich. Spring Boot as Jedis client libraries and client-based abstract Jedis provided by Spring Data Redis provides automatic configuration. spring-boot-starter-redis'Starter POM ' provides a convenient way to collect dependent.

Introducing spring-boot-starter-redis, increased configured as follows (based on a previous chapter "Spring Boot Framework Construction" in pom.xml file) in the pom.xml configuration file:

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-redis</artifactId>  
</dependency>

You may be injected into a RedisConnectionFactory automatic configuration, StringRedisTemplate or with other identical RedisTemplate Spring Bean Common examples. By default, this instance will try to use localhost: 6379 Redis server connection.
@Component
public class The MyBean {
Private StringRedisTemplate Template;

@Autowired
public MyBean(StringRedisTemplate template) {
    this.template = template;
}
// ...

}
If add a configuration of any type of own automatic @Bean, it will replace the default (except in the case RedisTemplate, which is based on the name of the bean 'redisTemplate' rather than its types excluded). If there commons-pool2 at the classpath, default factory to obtain a connection pool.

Redis application use cases
to add profile configuration as follows:

# REDIS (RedisProperties)
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379  
# 连接超时时间(毫秒)
spring.redis.timeout=0

redis configuration class, specific code as follows:
Import org.springframework.boot.context.properties.ConfigurationProperties;
Import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = “spring.redis”)
public class RedisConn {

private String host;  

private int port;  

private int timeout;  


public String getHost() {  
    return host;  
}  

public void setHost(String host) {  
    this.host = host;  
}  

public int getPort() {  
    return port;  
}  

public void setPort(int port) {  
    this.port = port;  
}  

public int getTimeout() {  
    return timeout;  
}  

public void setTimeout(int timeout) {  
    this.timeout = timeout;  
}  

@Override  
public String toString() {  
    return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]";  
}  

}
Note: annotation RedisConn class action @ConfigurationProperties (prefix = "spring.Redis") is an information read springboot default profile information to spring.redis beginning.

配置cache类
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import com.cachemodle.RedisConn;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
*
* @author sandsa redis cache service
*
*/

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

@Autowired
private RedisConn redisConn;

/ **
* production of key strategies
*
* @return
* /

@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {

       @Override  
       public Object generate(Object target, Method method, Object... params) {  
           StringBuilder sb = new StringBuilder();  
           sb.append(target.getClass().getName());  
           sb.append(method.getName());  
           for (Object obj : params) {  
               sb.append(obj.toString());  
           }  
           return sb.toString();  
       }  
   };  

}

/ **
* cache management
*
* @param redisTemplate
* @return
* /

@SuppressWarnings ( "rawtypes")
@Bean
public the CacheManager the CacheManager (RedisTemplate redisTemplate) {
RedisCacheManager new new RedisCacheManager = RCM (redisTemplate);
// set the cache expiration time, time in seconds
rcm.setDefaultExpiration (60);
the Map

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

Session configuration, the specific code as follows:
@Configuration
@EnableRedisHttpSession (maxInactiveIntervalInSeconds * 30 = 86400)
public class SessionConfig {
}
maxInactiveIntervalInSeconds: Set Session expiration time, after use the Redis Session, the original Spring Boot server.session.timeout property is no longer effective.

Test Examples, specific code as follows:
@RequestMapping ( "UID")
String UID (the HttpSession the session) {
the UUID UID = (the UUID) session.getAttribute ( "UID");
IF (UID == null) {
UID = UUID.randomUUID ( );
}
session.setAttribute ( "uid", uid);
return session.getId ();
}
is logged redis server, enter the command keys 'session *', see cache success.
Recommended ↓↓↓↓↓↓
Write pictures described here
more suggestions: micro-channel public number "leisurely"
concern the public micro-channel number "leisurely" (w_z90110), reply receive information Keywords: such as Hadoop, Dubbo, CAS source so on, receive free video and data projects.
Micro-channel public numbers of the Covered: Program life, funny videos, algorithms and data structures, hacking and network security, front-end development, Java, Python, Redis cache, spring source, the major mainstream framework, Web developers, big data technology, Storm, Hadoop , MapReduce, Spark, elasticsearch, unified authentication single sign-on, distributed framework, clusters, Android development, iOS development, C / C ++ ,. NET, Linux, MySQL, Oracle, NoSQL non-relational databases, operation and maintenance.

Published 35 original articles · won praise 48 · Views 150,000 +

Guess you like

Origin blog.csdn.net/afreon/article/details/78361176