Springboot (iii): Use of Redis in Spring boot

Source: Internet
Author: User
Tags assert sessions uuid

Objective:

This article is about the use of Redis in spring boot, which has not been used in the project before, so there is not much to feel, and you may need to go back and take a closer look later.

The original source: pure smile

Springboot to the common database support, the NoSQL database is also encapsulated automation.

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. Adding configuration Files

# REDIS (RedisProperties)

# Redis数据库索引(默认为0

spring.redis.database=0

# Redis服务器地址

spring.redis.host=192.168.0.58

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password= 

# 连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接

spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接

spring.redis.pool.min-idle=0

# 连接超时时间(毫秒)

spring.redis.timeout=0

3. Add the Cache configuration class

@Configuration

@EnableCaching

publicclass RedisConfig extends CachingConfigurerSupport{

@Bean

publicKeyGenerator keyGenerator() {

returnnew KeyGenerator() {

@Override

publicObject generate(Object target, Method method, Object... params) {

StringBuilder sb = newStringBuilder();

sb.append(target.getClass().getName());

sb.append(method.getName());

for(Object obj : params) {

sb.append(obj.toString());

}

returnsb.toString();

}

};

}

@SuppressWarnings("rawtypes")

@Bean

publicCacheManager cacheManager(RedisTemplate redisTemplate) {

RedisCacheManager rcm = newRedisCacheManager(redisTemplate);

//设置缓存过期时间

//rcm.setDefaultExpiration(60);//秒

returnrcm;

}

@Bean

publicRedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

StringRedisTemplate template = newStringRedisTemplate(factory);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = newJackson2JsonRedisSerializer(Object.class);

ObjectMapper om = newObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

jackson2JsonRedisSerializer.setObjectMapper(om);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

returntemplate;

}

}

4, OK, then you can directly use the

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(Application.class)

publicclass TestRedis {

@Autowired

privateStringRedisTemplate stringRedisTemplate;

@Autowired

privateRedisTemplate redisTemplate;

@Test

publicvoid test() throws Exception {

stringRedisTemplate.opsForValue().set("aaa", "111");

Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));

}

@Test

publicvoid testObj() throws Exception {

User user=newUser("[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");

booleanexists=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());

}

}

These are the manual use of the way, how to find the database automatically use the cache, see below;

5. Automatically generate cache based on method

@RequestMapping("/getUser")

@Cacheable(value="user-key")

publicUser getUser() {

User user=userRepository.findByUserName("aa");

System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功"); 

returnuser;

}

Where value is the key that is cached in Redis

Share Session-spring-session-data-redis

In distributed systems, Sessiong sharing has a number of solutions, where hosting into the cache should be one of the most common scenarios,

Spring Session Official Description

Spring session provides an APIs and implementations for managing a user ' s session information.

How to use

1. Introduction of dependency

<dependency>

<groupId>org.springframework.session</groupId>

<artifactId>spring-session-data-redis</artifactId>

</dependency>

2. Session Configuration:

@Configuration

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)

publicclass SessionConfig {

}

Maxinactiveintervalinseconds: Set session Expiration time, after using Redis session, the Server.session.timeout property of the original boot is no longer valid

Okay, so it's configured, let's test it.

3. Testing

Add test method Get SessionID

@RequestMapping("/uid")

String uid(HttpSession session) {

UUID uid = (UUID) session.getAttribute("uid");

if(uid == null) {

uid = UUID.randomUUID();

}

session.setAttribute("uid", uid);

returnsession.getId();

}

Login to Redis input keys ' *sessions* '

t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4

t(spring:session:expirations:1472976480000

1472976480000 is the expiration time, meaning the session expires after this time, DB031986-8ECC-48D6-B471-B137A3ED6BC4 for SessionID, login http://localhost:8080/ The UID discovery will be consistent, indicating that the session has been effectively managed in Redis.

How to share a session in two or more Taichung

In fact, according to the above steps in another project is configured again, automatically after the start of the session to share.

Sample code

Reference
    • Two typical application scenarios for Redis
    • Distributed sessions for Pringboot applications

Springboot (iii): 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.