redis

0、命令行操作

进入redis容器,输入命令进入redis命令行

redis-cli -a 密码
//查看所有key
keys *

1、jedis

导入依赖

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

代码实现

 @Test
    public void testRedis(){
        //1 获取连接
        Jedis jedis = new Jedis("101.37.17.237", 6379);
        jedis.auth("ShaoZeng1997");
        //2 执行操作
        //字符串类型
        jedis.set("name","lei");
        String name = jedis.get("name");
        System.out.println(name);
        jedis.del("name");
        //hash结构的数据
        jedis.hset("myhash","keyy","valuee");
        String hget = jedis.hget("myhash", "keyy");
        System.out.println(hget);
        //获取所有的key
        Set<String> keys = jedis.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }
        //3 关闭连接
        jedis.close();
    }

2、Spring Data Redis

image-mpcr.png

引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

配置参数

application.yml
spring:
  application:
    admin: redisdemo

  redis:
    host: 101.37.17.237
    port: 6379
    database: 0
    password: ShaoZeng1997
    jedis:
      pool:
        max-active: 8
        max-wait: 1ms
        max-idle: 4
        min-idle: 0

代码实现

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedis {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testsdr(){
        redisTemplate.opsForValue().set("city1111","changzhou");
    }
}

image-hrof.pngkey出现乱码是序列化的问题,如果不去底层看的话就无所谓,因为sping data redis会自动序列化和反序列化,实在看着不爽,可以加一个配置类,修改序列化方法。

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object,Object> redisTemplate =new RedisTemplate<>();
        //默认的序列化器是JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }
}