栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合Redis,通过程序将对象写入redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合Redis,通过程序将对象写入redis

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

(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 {
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    
    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);
        }
    }
    
    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 "存入成功";
    }

    @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

完事儿~ 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859985.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号