Spring Boot (iii) use of Redis in spring boot

Source: Internet
Author: User
Tags assert sessions uuid redis server



Spring boot also encapsulates the NoSQL database by automating the usual database support.


About Redis


Redis is the most widely used memory data store in the industry today. Supports a richer data structure than memcached,redis, such as hashes, lists, sets, etc., while supporting data persistence. In addition to this, Redis also provides some features of the class database, such as transactions, HA, and master-slave libraries. It can be said that Redis has a number of features of the cache system and database, so it has a rich application scenario. This article describes the two typical applications of Redis in spring boot.


How to use


1. Introduction of Spring-boot-starter-redis

<dependency>
    <groupId> org.springframework.boot </ groupId>
    <artifactId> spring-boot-starter-redis </ artifactId>
</ dependency>
2. Add configuration file

# REDIS (RedisProperties)
# Redis database index (default is 0)
spring.redis.database = 0
# Redis server address
spring.redis.host = 192.168.0.58
# Redis server connection port
spring.redis.port = 6379
# Redis server connection password (default is blank)
spring.redis.password =
# Maximum number of connections in the connection pool (use a negative value to indicate no limit)
spring.redis.pool.max-active = 8
# Connection pool maximum blocking wait time (use a negative value to indicate no limit)
spring.redis.pool.max-wait = -1
# The largest idle connection in the connection pool
spring.redis.pool.max-idle = 8
# The smallest idle connection in the connection pool
spring.redis.pool.min-idle = 0
# Connection timeout time (ms)
spring.redis.timeout = 0
3. Add cache configuration class

@Configuration
// This annotation will call RedisAutoConfiguration of Spring boot to initialize RedisTemplate and StringRedisTemplate
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    
    @Bean
    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 ();
            }
        };
    }

    @SuppressWarnings ("rawtypes")
    @Bean
    public CacheManager cacheManager (RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager (redisTemplate);
        // Set the cache expiration time
        //rcm.setDefaultExpiration(60);//sec
        return rcm;
    }
    
    @Bean
    public RedisTemplate <String, String> redisTemplate (RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate (factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class);
        ObjectMapper om = new ObjectMapper ();
        om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper (om);
        template.setValueSerializer (jackson2JsonRedisSerializer);
        template.afterPropertiesSet ();
        return template;
    }

}
3. Okay, then you can use it directly

@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (Application.class)
public class TestRedis {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test () throws Exception {
        stringRedisTemplate.opsForValue (). set ("aaa", "111");
        Assert.assertEquals ("111", stringRedisTemplate.opsForValue (). Get ("aaa"));
    }
    
    @Test
    public void testObj () throws Exception {
        User user = new User ("[email protected]", "aa", "aa123456", "aa", "123");
        ValueOperations <String, User> operations = redisTemplate.opsForValue ();
        operations.set ("com.neox", user);
        operations.set ("com.neo.f", user, 1, TimeUnit.SECONDS);
        Thread.sleep (1000);
        //redisTemplate.delete("com.neo.f ");
        boolean exists = redisTemplate.hasKey ("com.neo.f");
        if (exists) {
            System.out.println ("exists is true");
        } else {
            System.out.println ("exists is false");
        }
       // Assert.assertEquals ("aa", operations.get ("com.neo.f"). GetUserName ());
    }
}
The above are all manual methods. How to automatically use the cache when looking up the database? See below;

4. Automatically generate cache according to the method

@RequestMapping ("/ getUser")
@Cacheable (value = "user-key")
public User getUser () {
    User user = userRepository.findByUserName ("aa");
    System.out.println ("If the words" Call when there is no cache "do not appear below and the data can be printed to indicate that the test was successful");
    return user;
}
The value of value is the key cached in redis

Shared Session-spring-session-data-redis
In a distributed system, there are many solutions for sessiong sharing, and hosting to the cache should be one of the most commonly used solutions.

Spring Session official description
Spring Session provides an API and implementations for managing a user ’s session information.

how to use
1. Introduce dependencies

<dependency>
    <groupId> org.springframework.session </ groupId>
    <artifactId> spring-session-data-redis </ artifactId>
</ dependency>
2. Session configuration:

@Configuration
@EnableRedisHttpSession (maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {
}
maxInactiveIntervalInSeconds: Set the session expiration time, after using Redis Session, the original Boot server.session.timeout property no longer takes effect

Okay, so it ’s configured, let ’s test

3. Test

Add test method to get sessionid

@RequestMapping ("/ uid")
    String uid (HttpSession session) {
        UUID uid = (UUID) session.getAttribute ("uid");
        if (uid == null) {
            uid = UUID.randomUUID ();
        }
        session.setAttribute ("uid", uid);
        return session.getId ();
    }
Log in to redis and enter keys ‘* sessions *’

t <spring: session: sessions: db031986-8ecc-48d6-b471-b137a3ed6bc4
t (spring: session: expirations: 1472976480000
Among them, 1472976480000 is the expiration time, which means that the session will expire after this time. Db031986-8ecc-48d6-b471-b137a3ed6bc4 is the sessionId. Log in http: // localhost: 8080 / uid and find that they will be consistent, indicating that the session has been validated in redis Managed.

How to share session between two or more
In fact, it is configured again in another project according to the above steps, and session sharing is automatically performed after startup.

Spring boot (3) Use of Redis in Spring boot

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.