微人事第六天:springboot操作redis

java中操作redis的方法有很多,最主要使用的就是 Spring Data Redis。
在ssm中需要开发者自己来配置 Spring Data Redis ,这个配置比较繁琐,主要配置 3 个东西:连接池、连接器信息以及 key 和 value 的序列化方案。

在 Spring Boot 中,默认集成的 Redis 就是 Spring Data Redis,默认底层的连接池使用了 lettuce ,开发者可以自行修改为自己的熟悉的,例如 Jedis。
在这里插入图片描述
Spring Data Redis 针对 Redis 提供了非常方便的操作模板 RedisTemplate 。这是 Spring Data 擅长的事情,那么接下来我们就来看看 Spring Boot 中 Spring Data Redis 的具体用法。

1.创建springboot工程
勾选web,Security,redis
在这里插入图片描述

2配置redis基础信息
配置redis的主地址,端口,密码等信息

spring.redis.host=192.168.0.101
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=123

3.启动redis
进入系统管理界面,进入redis安装包的目录下
运行命令:redis-server.exe redis.windows.conf
在这里插入图片描述
4.编写对redis的操作
RedisAutoConfiguration中有两个bean:RedisTemplate和StringRedisTemplate
在这里插入图片描述
@Configuration又是一个配置类
在这里插入图片描述
所以在controller中可以注入StringRedisTemplate。

Redis 中的数据操作,大体上来说,可以分为两种:
针对 key 的操作,相关的方法就在 RedisTemplate 中
针对具体数据类型的操作,相关的方法需要首先获取对应的数据类型,获取相应数据类型的操作方法是 opsForXXX

package org.javaboy.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/set")
    public void set() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("name","javaboy");
    }

    @GetMapping("/get")
    public void get() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        System.out.println(ops.get("name"));
    }
}

4测试
启动之后访问http://localhost:8080/set后跳转登陆界面:
在这里插入图片描述
因为之间创建工程时引入了security(这是一种安全保护机制),用户名为user,密码在控制台中出现随机:在这里插入图片描述
登陆之后再访问:http://localhost:8080/get
控制台打印:javaboy

发布了287 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41998938/article/details/104083009
今日推荐