Spring boot (11) redis integration is installed from docker to distributed session sharing
1、 Introduction
Redis is an open-source log type key value database written in ANSI C language, supporting network, memory based and persistent, and provides APIs in multiple languages. Redis is also the most widely used storage Middleware in the technical field. It is the acronym of "remote dictionary service", that is, "remote dictionary service".
Redis provides more data type support and data persistence operations than memcached.
2、 Install redis in docker
Visit the official website: https://hub.docker.com/r/library/redis/ Select the download version, and select the latest stable 4.0 eleven
Use the command to pull the image:
2.2 startup vessel
The command to start redis is as follows:
Command description:
After successful startup, use the command:
View the redis running request. The following figure shows the successful running:
2.3 using client connections
A good GUI tool for connecting to redis should be redis Desktop Manager, but now only the Linux version can be downloaded for free. I uploaded a Windows version in Baidu cloud. The version number is 0.9 5 (released on August 24, 2018) is also relatively new. Link: https://pan.baidu.com/s/16npZtnGa3-p2PAafiPEAkA Password: 9uqg, installation free, easy to use.
Redis desktop manager client Preview:
3、 Redis integration
development environment
3.1 adding dependencies
In POM Add the following dependencies to XML:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Be careful not to rely on "spring boot starter redis", which is an old version. The new version has been migrated to "spring boot starter data redis".
3.2 configuring redis
In application Properties are set as follows:
# Redis 配置
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接密码(默认为空)
spring.redis.password=
# Redis服务器连接端口
spring.redis.port=6379
# Redis分片(默认为0)Redis默认有16个分片
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
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=10000
# 指定spring的缓存为redis
spring.cache.type=redis
Note: spring redis. Do not set timeout to 0. If it is set to 0, an error will be reported when querying redis, because the query connection time is too short.
3.3 redis usage
After completing the above configuration, you can write code to operate redis. The example code is as follows:
@Autowired
private StringRedistemplate stringRedistemplate;
@RequestMapping("/")
public String dotest() {
String _key = "time"; //缓存key
stringRedistemplate.opsForValue().set(_key,String.valueOf(new Date().getTime())); //redis存值
return stringRedistemplate.opsForValue().get(_key); //redis取值
}
More actions:
4、 Declarative cache
In order to simplify the cache, you can directly use the reputation cache. You can save the code for setting the cache and reading the cache, which will be much more convenient to use.
The steps for using declarative cache are as follows:
4.1 setting redis cache
In POM The XML file is set as redis, and the code is as follows:
4.2 enable global cache
In the startup file application Java settings enable caching. The code is as follows:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
4.3 use notes
Notes are as follows:
General properties:
4.3. 1 @ cacheable use
The example code is as follows:
// 缓存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/")
@Cacheable(value = _CacheKey)
public String index() {
System.out.println("set cache");
return "cache:" + new Date().getTime();
}
The "set cache" information will be printed on the console only during the first access, and then the redis result will be returned directly. The added print information will not appear.
4.3. 2 @ cacheput usage
The example code is as follows:
// 缓存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/put")
@CachePut(value = _CacheKey)
public String putCache() {
System.out.println("update cache");
return "update cache:" + new Date().getTime();
}
visit http://xxx/put The latest data will be stored and cached each time.
4.3. 3 @ cacheevict usage
The example code is as follows:
// 缓存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/del")
@CacheEvict(value = _CacheKey)
public String delCache() {
System.out.println("缓存删除");
return "delete cache:" + new Date().getTime();
}
visit http://xxx/del Only the cache will be deleted, and nothing will be done after that.
5、 Distributed session sharing
There are many schemes for session sharing in distributed systems, and hosting session in cache is one of the most commonly used schemes. Let's look at the hosting steps of session in redis.
5.1 adding dependencies
In POM Add the following reference to XML:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
5.2 enable session function
In the startup class application Add the class annotation of Java to start the session. The code is as follows:
@SpringBootApplication
@EnableCaching
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class,args);
}
}
Where maxinactivivilinseconds is the expiration time of the session. The default is 30 minutes. The setting unit is seconds.
5.3 session usage
Next, write a piece of code to test the session. The example code is as follows:
@RequestMapping("/uid")
public String testSession(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid",uid);
return session.getId();
}
After two consecutive requests, view the console information as shown in the figure below:
It can be seen that the sessionid of the two accesses is the same. At this time, view the redis client, as shown in the following figure:
It is found that the session expiration time stored in redis is also correct, which conforms to our settings.
5.4 distributed system sharing session
Because the session is hosted to the same redis server, the session is configured with multiple servers in spring boot as described above, and the sessions are the same.
Sample source code download: https://github.com/vipstone/springboot-example/tree/master/springboot-redis
reference material
Use of redis in spring boot: http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html