从零开始学习Redis(三)代码使用Redis

1.安装完了之后就可以使用了,我是用的是SpringBoot整合Redis。咱们整个最简单的。新建一个maven项目,添加依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!--使用lettuce时,需要额外引入commons-pool2依赖包-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.添加配置文件

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 500
        min-idle: 0

3.添加Redis的配置文件

@Configuration
public class RedisConfig {    //Rdis配置工具,包括序列器配置等
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> template=new RedisTemplate<>();
        //关联
        template.setConnectionFactory(factory);
        //设置key的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        //设置value的序列器
        template.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        return template;
        }
}

4.测试

经验分享 程序员 微信小程序 职场和发展