SpringBoot整合Redis将对象写入redis的实现(spring boot整合redis)

网友投稿 407 2022-07-27


目录1、环境搭建 2、代码编写3、测试

1、环境搭建

创建一个SpringBoot项目,普通的web项目就可以了,我这里使用的是start.aliyun

引入依赖:

(1)老演员了不多说。

org.springframework.boot

spring-boot-starter-web

(2)整合redis

org.springframework.boot

spring-boot-starter-data-redis

(3) 实体类用到了@Data注解

org.projectlombok

lombok

true

</dependency>

(4)将对象转为json存入redis,取出来时将json转为对象

com.alibaba

fastjson

1.2.30

2、代码编写

(1)在Application启动类的同级目录下创建对应的包

(2)写redis工具类

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component

public class RedisUtils {

/**

* 获取redis模板

*/

@Autowired

private StringRedisTemplate stringRedisTemplate;

/**

* 存入String类型

* @param key

* @param value

* @param timeOut

*/

http:// public void setString(String key, String value, Long timeOut){

stringRedisTemplate.opsForValue().set(key, value);

if (timeOut != null){

//设置Redis的key的有效期

stringRedisTemplate.expire(key, timeOut, TimeUnit.SECONDS);

}

}

/**

* 获取String类型

* @paraEFttffgm key

* @return

*/

public String getString(String key){

return stringRedisTemplate.opsForValue().get(key);

}

}

实体类:

import lombok.Data;

@Data

public class User {

private String name;

private Integer age;

}

控制层:

import com.alibaba.fastjson.JSONObject;

import com.example.redis.redistudy.pojo.User;

import com.example.redis.redistudy.util.RedisUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class RedisController {

@Autowired

private RedisUtils redisUtils;

@GetMapping("/addUser")

public String addUser(){

User user = new User();

user.setName("zhangsan");

user.setAge(18);

String userString = JSONObject.toJSONString(user);

redisUtils.setString("userString",userString, null);

return "存入成功";

http:// }

@GetMapping("/getUser")

public User getUser(String key){

String userString= redisUtils.getString(key);

User user = JSONObject.parseObject(userString, User.class);

return user;

}

}

(3)yml文件配置

spring:

redis:

host: 服务器公网ip

password: root //密码

port: 6379 //端口号

database: 0 //指定存入哪一个库

3、测试

启动程序 ,访问地址:http://localhost:8080/addUser

看一下redis,存入成功

再获取一下,获取成功

地址:http://localhost:8080/getUser?key=userString


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot项目打包成jar包的图文教程(springboot如何打成jar包?)
下一篇:关于easyExcel中读取Excel表头的实例说明(easyexcel自定义表头)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~