In addition to supporting the commonly used databases, spring boot also encapsulates and automates the nosql database.
Introduction to redis
Redis is currently the most widely used in-memory data store in the industry. Compared with memcached, Redis supports richer data structures, such as hashes, lists, sets, etc., and supports data persistence. In addition, Redis also provides some database-like features, such as transactions, HA, and master-slave libraries. It can be said that Redis has both the characteristics of the cache system and the database, so it has rich application scenarios. This article introduces two typical application scenarios of Redis in Spring Boot.
how to use
1. Introduce spring-boot-starter-redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2. Add a configuration file
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.1.111
# 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 cache configuration class
@Configuration
@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);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
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;
}
}
4. 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("A", "1");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("A"));
}
@Test
public void testObj() throws Exception {
User user=new User("[email protected]", "test", "123456", "test","123456");
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;
5. Automatically generate cache according to method
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}
The value of value is the key cached in redis
共享Session-spring-session-data-redis
In distributed systems, there are many solutions for sessiong sharing, of which hosting in the cache should be one of the most commonly used solutions.
Official description of Spring Session
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 server.session.timeout property of the original Boot will no longer take effect.
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();
}
Login to redis input 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. It db031986-8ecc-48d6-b471-b137a3ed6bc4
is the sessionId. If you log in to http://localhost:8080/uid and find that it will be consistent, it means that the session has been effectively managed in redis.
How to share session between two or more
Follow the above steps to configure it again in another project, and session sharing is automatically performed after startup.