1
头图

What is redis?

Simply put, redis is an open source memory database written in ANSI C key-value data structure. Support data persistence to hard disk, support multiple api language connections. Usually treated as a cache.

Install redis

  1. official website: 1610b857779ceb https://redis.io English official website, download the linux version redis
  2. redis for windows: https://github.com/MicrosoftArchive/redis/releases , the windows version can be downloaded to the local and installed directly.

After the windows version is downloaded and installed, the redis service can be seen in services.msc.

springboot integrated redis

We use the redisson framework to integrate, create a new project, and add the following dependencies to the pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.15.0</version>
</dependency>

Modify the application.yml file and add redis configuration

spring:
  redisson:
    address: redis://127.0.0.1:6379 #redis的地址和端口,默认端口是6379
    password: #默认没有买卖
    database: 0 #Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
    timeout: 10000 #连接超时时间(毫秒)

Add a configuration class to map the properties in the yml file

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.redisson")//获取yml文件中以spring.redisson开头的所有数据
public class RedissonProperties {
    //映射yml文件里面的数据
    private String address;
    private String password = null;
    private int database = 0;
    private int timeout = 3000;
}

Add RedissonClient initialization class:

@Configuration
@ConditionalOnClass(RedissonClient.class)//存在RedissonClient才创建该类
@ConditionalOnProperty({"spring.redisson.address"})//存在spring.redisson.address配置才创建该类
public class RedissonConfig {

    @Resource
    private RedissonProperties properties;

    @Bean(destroyMethod = "shutdown")
    RedissonClient redissonClient(RedissonProperties properties) throws Exception {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig
                .setAddress(properties.getAddress())
                .setDatabase(properties.getDatabase())
                .setTimeout(properties.getTimeout());
        //密码不为空才设置,否则默认yml注入的空串会导致创建redisson不成功
        if(!StringUtils.isEmpty(properties.getPassword())){
            singleServerConfig.setPassword(properties.getPassword());
        }

        return Redisson.create(config);
    }
}

Well, since then, the preparations are done, and now you can encode and operate redis data.

@RestController
@RequestMapping("demo")
public class DemoController {
    @Resource
    private RedissonClient redissonClient;

    public static String MAP_KEY = "MAP";
    public static String SET_KEY = "SET";
    public static String LIST_KEY = "LIST";

    @GetMapping("put")
    public String put(){
        RMap<String, String> map = redissonClient.getMap(MAP_KEY);
        map.put("a","hello redis");
        return "ok";
    }

    @GetMapping("get")
    public String get(){
        RMap<String, String> map = redissonClient.getMap(MAP_KEY);
        return map.get("a");
    }
}

First use postman to request http://localhost:8080/demo/put put the data in, and then find a redis ide tool (redis studio is used in this article) to view the data in redis

The data is put in, and the data can also be taken out by http://localhost:8080/demo/get . . That's because you didn't specify the serialization method when using redissonClient. Modify the code as follows:

RMap<String, String> map = redissonClient.getMap(MAP_KEY, JsonJacksonCodec.INSTANCE);

Try again to see how redis studio displays:

How about it, it's clear. Then RMap can only put basic data objects "Can you put custom objects? Create a dto:

@Data
public class UserDto implements Serializable {
    private String username;
    private Integer age;
    private Date birthday;
    private List<String> fav;
}

New rest method:

@GetMapping("put2")
public String put2(){
    RMap<String, UserDto> map = redissonClient.getMap(MAP_KEY, JsonJacksonCodec.INSTANCE);
    UserDto userDto = new UserDto();
    userDto.setUsername("张三6");
    userDto.setAge(18);
    userDto.setBirthday(new Date());
    userDto.setFav(Arrays.asList("apple","pear"));
    map.put("userDto",userDto);
    return "ok";
}

@GetMapping("get2")
public UserDto get2() throws InterruptedException {
    RMap<String, UserDto> map = redissonClient.getMap(MAP_KEY, JsonJacksonCodec.INSTANCE);
    UserDto userDto = map.get("userDto");
    return userDto;
}

Play the card according to the routine, request it by postman, and then look at the data of redis studio:

How about, feel comfortable, the objects are all stored in by you, and you can take them out of redis and convert them into UserDto objects! ! !

Well, the above is the RMap object. I won't explain in detail the list and set below, just go to the code.

@GetMapping("put3")
public String put3(){
    RSet<Long> set = redissonClient.getSet(SET_KEY, JsonJacksonCodec.INSTANCE);
    set.add(System.currentTimeMillis());
    return "ok";
}

@GetMapping("get3")
public String get3() throws InterruptedException {
    RSet<Long> set = redissonClient.getSet(SET_KEY, JsonJacksonCodec.INSTANCE);
    Iterator<Long> iterator = set.iterator();
    String result = "";
    while (iterator.hasNext()){
        result +=","+iterator.next();
    }
    return result;
}

@GetMapping("put4")
public String put4(){
    RList<Long> list = redissonClient.getList(LIST_KEY, JsonJacksonCodec.INSTANCE);
    list.add(1L);
    return "ok";
}

@GetMapping("get4")
public String get4() throws InterruptedException {
    RList<Long> list = redissonClient.getList(LIST_KEY, JsonJacksonCodec.INSTANCE);
    String result="";
    for (Long aLong : list) {
        result+=aLong;
    }
    return result;
}

Every time I have to write JsonJacksonCodec.INSTANCE 1610b85777b5fa This thing is very annoying, forget it, The default JsonJacksonCodec.INSTANCE serialization. Then we modify the config.

@Bean(destroyMethod = "shutdown")
RedissonClient redissonClient(RedissonProperties properties) throws Exception {
    Config config = new Config();
    SingleServerConfig singleServerConfig = config.useSingleServer();
    singleServerConfig
            .setAddress(properties.getAddress())
            .setDatabase(properties.getDatabase())
            .setTimeout(properties.getTimeout());
    //密码不为空才设置,否则默认yml注入的空串会导致创建redisson不成功
    if(!StringUtils.isEmpty(properties.getPassword())){
        singleServerConfig.setPassword(properties.getPassword());
    }
    //指定默认序列化
    Codec codec=(Codec) ClassUtils.forName("org.redisson.codec.JsonJacksonCodec", ClassUtils.getDefaultClassLoader()).newInstance();
    config.setCodec(codec);
    return Redisson.create(config);
}

Let's try to call redis without specifying serialization:


@GetMapping("test")
public String test(){
    RMap<String, UserDto> map = redissonClient.getMap("MAP_KEY");
    UserDto userDto = new UserDto();
    userDto.setUsername("张三6d");
    userDto.setAge(18);
    userDto.setBirthday(new Date());
    userDto.setFav(Arrays.asList("apple","pear"));
    map.put("userDto",userDto);
    return "ok";
}

Is it garbled? It's not garbled.

The usefulness of redis is far from that. You can also set the cached data validity period, how long it will be valid, and monitor the creation, modification, and destruction of data events. In addition, there are queues, publish subscriptions, etc. waiting for everyone to explore.

To sum up, redis is very useful as a cache, but even if it is a persistent database, he is not born for that!

More java original reading: https://javawu.com

大盛玩java
24 声望5 粉丝