springBoot(8)---整合redis


Springboot整合redis

 

步驟講解

 

 1、第一步jar導入:

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

      如果你本地沒有相應jar包,你可以在mevan存放jar包的庫中,找到Setting文件,添加阿里雲鏡像,在跟新就可以下載相應jar包

       <mirror>
            <id>alimaven-central</id>
            <mirrorOf>central</mirrorOf>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
        </mirror>

 

第二步:application.properties配置

            spring.redis.database=0
            spring.redis.host=127.0.0.1
            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
配置

 

第三步創建實體

    User類

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;
    }
}
User類

JsonData工具類實體

/**
 * 這是后端向前端響應的一個包裝類
 * 一般后端向前端傳值會有三個屬性
 * 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、字符串轉對象,對象轉字符串工具類

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類

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類

RdisTestController

import java.util.Date;


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.jincou.model.JsonData;
import com.jincou.model.User;
import com.jincou.until.JsonUtils;
import com.jincou.until.RedisClient;

@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();
        
    }
    
    //通過key值得到value字符串
    @GetMapping(value="get")
    public Object get(){
        
        String value = redis.get("username");
        return JsonData.buildSuccess(value);
        
    }
    
    //將對象通過工具類轉成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);
        
    }
    
    //通過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);
        
    }        
}

 

測試效果

命名規范:如果我們key按"base:user:11"這來命名,那么那么會自動創建文件夾格式,方便查看。

 
        

 

 想太多,做太少,中間的落差就是煩惱。想沒有煩惱,要么別想,要么多做。上尉【10】

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM