Redis工具类封装及使用

1.新建springboot项目,bom.xml添加依赖

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <version>2.6.7</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

 2.新建实体类

package com.xiaobing.domain;
import java.util.Date;

public class User {
    private int age;
    private String pwd;
    private String phone;
    private Date createTime;

    public User() {
    }
    public User(int age, String pwd, String phone, Date createTime) {
        this.age = age;
        this.pwd = pwd;
        this.phone = phone;
        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 Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", pwd='" + pwd + '\'' +
                ", phone='" + phone + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}
package com.xiaobing.domain;
public class JsonData {
    
    private int code;
    private Object data;
    private String msg;
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public JsonData(int code, Object data) {
        super();
        this.code = code;
        this.data = data;
    }
    public JsonData(int code, Object data, String msg) {
        super();
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    public JsonData() {
        super();
    }
    public static JsonData buildSuccess(Object data) {
        return new JsonData(0, data);
    }
    public static JsonData buildSuccess(Object data,String msg) {
        return new JsonData(0, data,msg);
    }    
    public static JsonData buildError(String msg) {
        
        return new JsonData(-1, "", msg);
    }  
    public static JsonData buildError(String msg,int code) {
        
        return new JsonData(code, "", msg);
    }
    @Override
    public String toString() {
        return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg + "]";
    }
}

3.JsonUtils 对象转字符串,字符串转对象工具类

package com.xiaobing.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

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 (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

4.Redis工具类

package com.xiaobing.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisClient {
    @Autowired
    private StringRedisTemplate redisTpl;

    /**
     * 设置key-value到Redis中
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key , String value){
        try {
            redisTpl.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 通过key获取缓存中的值
     * @param key
     * @return
     */
    public String get(String key){
        try {
            return redisTpl.opsForValue().get(key);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

5.Redis配置文件application.properties

server.port=9090      
#redis基础配置
spring.redis.database=0
spring.redis.host=xx.xx.xx.xx
spring.redis.port=6379
#连接超时时间单位Ms(毫秒)
spring.redis.timeout=3000
#=====redis线程池设置======
#连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=200
#连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=200
#如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=2000
#等待可用连接的最大时间,单位毫秒,默认值为一1,表示永不超时
spring.redis.pool.max-wait=1000

6. Controller

package com.xiaobing.controller;

import com.xiaobing.domain.JsonData;
import com.xiaobing.domain.User;
import com.xiaobing.utils.JsonUtils;
import com.xiaobing.utils.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 java.util.Date;

@RestController
@RequestMapping("api/v1/pub")
public class TestController {

    @Autowired
    private RedisClient redisClient;

    User user = new User(1,"123456","1008611",new Date());

    @GetMapping(value="set_user")
    public JsonData setUser(){
        boolean result = redisClient.set("base:user:"+user.getPhone(), JsonUtils.obj2String(user));
        return JsonData.buildSuccess(result,"SET成功");
    }
    @GetMapping(value="get_user")
    public JsonData getUser(){
        String str = redisClient.get("base:user:"+user.getPhone());
        User user = JsonUtils.string2Obj(str,User.class);
        return JsonData.buildSuccess(user,"GET成功");
    }
}

7.启动类

package com.xiaobing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

8.启动访问

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)
2022-07-12 16:17:43.864  INFO 17080 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9099 (http) with context path ''
2022-07-12 16:17:43.867  INFO 17080 --- [           main] com.xiaobing.DemoApplication             : Started DemoApplication in 4.582 seconds (JVM running for 5.202)

 9.Redis客户端查看验证

 10.自测,以备方便后续使用!

 

posted @ 2022-07-12 16:31  o小兵o  阅读(742)  评论(0编辑  收藏  举报