Redis Initialization

Posted by Jordon Li on Friday, April 3, 2020

TOC

Redis简介

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.

Redis是一个开源的基于内存的数据结构存储器,可以用作数据库缓存和消息中间件

Redis application scenario

  • 缓存
    • 第一次读取数据的时候,会触发程序读取数据库,把数据读取出来,并且写入 Redis 中
    • 第二次以及以后需要读取数据时,就会直接读取 Redis,这样速度就大大提高了
  • 高速读/写的场合
    • 当一个请求到达服务器时,只是把业务数据在 Redis 上进行读写,而没有对数据库进行任何的操作,这样就能大大提高读写的速度,从而满足高速响应的需求
    • 但是这些缓存的数据仍然需要持久化,也就是存入数据库之中,所以在一个请求操作完 Redis 的读/写之后,会去判断该高速读/写的业务是否结束,如果结束,则触发事件将 Redis 的缓存的数据以批量的形式一次性写入数据库,从而完成持久化的工作

Installation Redis

  • github:https://github.com/ServiceStack/redis-windows/tree/master/downloads

  • Start redis server command:

    redis-server redis.windows.conf
    
  • try redis: http://try.redis.io/

Using Redis in SpringBoot

  • Add reference

    <!-- Radis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • Add configuration

    spring:
      redis:
        database: 1 # Redis数据库索引(默认为0)
    
        host: localhost # Redis服务器地址
    
        port: 6379 # Redis服务器连接端口
    
        encode: UTF-8
        password: longlianredis2020 # Redis服务器连接密码(默认为空)
    
        timeout: 60000 # 连接超时时间(毫秒)
    
        jedis:
          pool:
            max-active: 100 # 连接池最大连接数(使用负值表示没有限制)
    
            max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
    
            max-idle: 8 # 连接池中的最大空闲连接
    
            min-idle: 5 # 连接池中的最小空闲连接
    
    
  • Using RedisTemplate

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest()
    public class ApplicationTests {
      
        @Autowired
        private RedisTemplate redisTemplate;
      
        @Test
        public void test() throws Exception {
            User user = new User();
            redisTemplate.opsForValue().set("user_1", user);
            User user1 = (User) redisTemplate.opsForValue().get("user_1");
        }
    }
    

「下次一定」

下次一定

使用微信扫描二维码完成支付