• spring-集成redis


    第一步:jar导入

    pom.xml:

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

    第二步:application.properties配置

    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=localhost
    # Redis服务器连接端口
    spring.redis.port=6379
    # 连接超时时间 单位 ms(毫秒)
    spring.redis.timeout=3000
    # 连接池中的最大空闲连接,默认值也是8。
    spring.redis.pool.max-idle=8
    #连接池中的最小空闲连接,默认值也是0。
    spring.redis.pool.min-idle=0
    # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    spring.redis.pool.max-active=8
    # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
    spring.redis.pool.max-wait=-1

    第三步:创建实体

    model/User.java:User类

    package com.example.model;
    
    import java.util.Date;
    
    public class User {
    
        private int age;
    
        private String pwd;
    
        private String phone;
    
        private Date createTime;
    
    
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        public User() {
            super();
        }
    
        public User(int age, String pwd, String phone, Date createTime) {
            super();
            this.age = age;
            this.pwd = pwd;
            this.phone = phone;
            this.createTime = createTime;
        }
    }

    model/JsonData.java:json工具类

    package com.example.model;
    
    import java.io.Serializable;
    
    /**
     * 这是后端向前端响应的一个包装类
     * 一般后端向前端传值会有三个属性
     * 1:响应状态
     * 2:如果响应成功,把数据放入
     * 3: 描述,响应成功描述,或者失败的描述
     */
    public class JsonData implements Serializable {
    
    
        private static final long serialVersionUID = 1L;
    
        private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败
        private Object data; // 数据
        private String msg;// 描述
    
        public JsonData() {
        }
    
        public JsonData(Integer code, Object data, String msg) {
            this.code = code;
            this.data = data;
            this.msg = msg;
        }
    
        // 成功,只返回成功状态码
        public static JsonData buildSuccess() {
            return new JsonData(0, null, null);
        }
    
        // 成功,传入状态码和数据
        public static JsonData buildSuccess(Object data) {
            return new JsonData(0, data, null);
        }
    
        // 失败,传入描述信息
        public static JsonData buildError(String msg) {
            return new JsonData(-1, null, msg);
        }
    
        // 失败,传入描述信息,状态码
        public static JsonData buildError(String msg, Integer code) {
            return new JsonData(code, null, msg);
        }
    
        // 成功,传入数据,及描述信息
        public static JsonData buildSuccess(Object data, String msg) {
            return new JsonData(0, data, msg);
        }
    
        // 成功,传入数据,及状态码
        public static JsonData buildSuccess(Object data, int code) {
            return new JsonData(code, data, null);
        }
    
        //提供get和set方法,和toString方法
    }

    第四步:创建工具类

    1、字符串转对象,对象转字符串工具类

    until/JsonUtils.java

    package com.example.until;
    
    import java.io.IOException;
    
    import org.springframework.util.StringUtils;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    /**
     * 字符串转对象,对象转字符串的工具类
     * 因为StringRedisTemplate的opsForValue()方法需要key,value都需要String类型,所以当value值存入对象的时候
     * 先转成字符串后存入。
     */
    public class JsonUtils {
    
        private static ObjectMapper objectMapper = new ObjectMapper();
    
        //对象转字符串
        public static <T> String obj2String(T obj){
            if (obj == null){
                return null;
            }
            try {
                return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        //字符串转对象
        public static <T> T string2Obj(String str,Class<T> clazz){
            if (StringUtils.isEmpty(str) || clazz == null){
                return null;
            }
            try {
                return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    2.封装redis类

    until/RedisClient.java

    package com.example.until;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.stereotype.Component;
    
    /**
     * 功能描述:redis工具类
     * 对于redisTpl.opsForValue().set(key, value)进行了一次封装,不然每次都要这样保存值
     * 而封装后只需:new RedisClient().set(key,value);
     */
    @Component
    public class RedisClient {
        @Autowired
        private StringRedisTemplate redisTpl; //jdbcTemplate
    
        // 功能描述:设置key-value到redis中
        public boolean set(String key ,String value){
            try{
                redisTpl.opsForValue().set(key, value);
                return true;
            }catch(Exception e){
                e.printStackTrace();
                return false;
            }
        }
    
        // 功能描述:通过key获取缓存里面的值
        public String get(String key){
            return redisTpl.opsForValue().get(key);
        }
    
    }

    第五步:创建Controller类

    controller/RdisTestController.java

    package com.example.controller;
    
    import java.util.Date;
    
    
    import com.example.model.JsonData;
    import com.example.until.JsonUtils;
    import com.example.until.RedisClient;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.example.model.User;
    
    @RestController
    @RequestMapping("/api/v1/redis")
    public class RdisTestController {
    
    
        //得到redis封装类
        @Autowired
        private RedisClient redis;
    
        //添加字符串
        @GetMapping(value="add")
        public Object add(){
            redis.set("username", "xddddddd");
    //        return JsonData.buildSuccess();
            return "ok";
        }
    
        //通过key值得到value字符串
        @GetMapping(value="get")
        public Object get(){
    
            String value = redis.get("username");
    //        return JsonData.buildSuccess(value);
            return "ok";
        }
    
        //将对象通过工具类转成String类型,存入redis中
        @GetMapping(value="save_user")
        public Object saveUser(){
            User user = new User(1, "abc", "11", new Date());
            String userStr = JsonUtils.obj2String(user);
            boolean flag = redis.set("base:user:11", userStr);
    //        return JsonData.buildSuccess(flag);
            return "ok";
        }
    
        //通过key值得到value值,让后将value转为对象
        @GetMapping(value="find_user")
        public Object findUser(){
    
            String userStr = redis.get("base:user:11");
            User user = JsonUtils.string2Obj(userStr, User.class);
    //        return JsonData.buildSuccess(user);
            return "ok";
        }
    }
  • 相关阅读:
    转载:linux or unit 连接 windows的远程桌面-rdesktop(略有修改)
    Excel技巧
    Linux实用配置(ubuntu)
    转载:VMware linux 虚拟机中修改MAC地址
    windows技巧
    cdoj1099
    hdu1160(问题)
    c#学习笔记
    hdu1176
    qsort(),sort() scanf();
  • 原文地址:https://www.cnblogs.com/zhzhlong/p/10062729.html
Copyright © 2020-2023  润新知