十.SpringBoot中配置Redis

十.SpringBoot-Redis

1.POM配置

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.58version>
dependency>

2.application配置

#redis默认的数据库索引号,默认0
#redis密码默认为空
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:

3.使用

在SpringBoot整合redis中

提供了一个模板类StringRedisTemplate

@SpringBootTest
class SpringbootRedisApplicationTests {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        //判断key是否存在
//        System.out.println(redisTemplate.hasKey("aaa"));

        System.out.println("name的值为:"+redisTemplate.opsForValue().get("name"));

        //向Hash中存数据
//        Map map = new HashMap<>();
//        map.put("username","admin");
//        map.put("password","123456");
//        map.put("phone","13812345678");
//        map.put("address","江苏-南京");
//        map.put("id","1");
//        redisTemplate.opsForHash().putAll("map",map);

        User user = new User();
        user.setId(1);
        user.setUsername("admin");
        user.setPassword("666666");
        user.setPhone("13812345678");
        user.setAddress("江苏-南京");

        String userJson = JSON.toJSONString(user);
        redisTemplate.opsForValue().set("user",userJson);

    }

}

你可能感兴趣的:(Redis)