========================9、SpringBoot2.x整合Redis實戰 ================================
1、分布式緩存Redis介紹
簡介:講解為什么要用緩存和介紹什么是Redis,新手練習工具
通過緩存減少數據庫訪問,提高訪問速度
1、redis官網 https://redis.io/download
2、新手入門redis在線測試工具:http://try.redis.io/
2、源碼編譯安裝Redis4.x
簡介:使用源碼安裝Redis4.x和配置外網訪問
1、快速安裝 https://redis.io/download#installation
wget http://download.redis.io/releases/redis-4.0.9.tar.gz
tar xzf redis-4.0.9.tar.gz
cd redis-4.0.9
make
啟動服務端:src/redis-server
啟動客戶端:src/redis-cli
2、默認是本地訪問的,需要開放外網訪問
1)打開redis.conf文件在NETWORK部分修改
注釋掉bind 127.0.0.1可以使所有的ip訪問redis
修改 protected-mode,值改為no
查看當前占用端口
3、SpringBoot2.x整合redis實戰講解
簡介:使用springboot-starter整合reids實戰
1、官網:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-redis
集群文檔:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#cluster
2、springboot整合redis相關依賴引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3、相關配置文件配置
#=========redis基礎配置=========
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6390
# 連接超時時間 單位 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
4、常見redistemplate種類講解和緩存實操(使用自動注入)
1、注入模板
@Autowired
private StirngRedisTemplate strTplRedis
2、類型String,List,Hash,Set,ZSet
對應的方法分別是opsForValue()、opsForList()、opsForHash()、opsForSet()、opsForZSet()

package com.atguigu.springboot.controller; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.atguigu.springboot.controller.domain.JsonData; @RestController @RequestMapping("/api/v1/redis") public class RdisTestController { @Autowired private StringRedisTemplate redisTpl; //jdbcTemplate @GetMapping(value="add") public Object add(){ //opsForValue : Returns the operations performed on simple values (or Strings in Redis terminology). redisTpl.opsForValue().set("name", "xdclass2018"); return JsonData.buildSuccess(); } @GetMapping(value="get") public Object get(){ String value = redisTpl.opsForValue().get("name"); return JsonData.buildSuccess(value); } }
4、Redis工具類封裝講解和實戰
簡介:高效開發方式 Redis工具類封裝講解和實戰
1、常用客戶端 https://redisdesktop.com/download
2、封裝redis工具類並操作
utils用於 對象 轉str str轉對象

package net.xdclass.base_project.utils; import java.io.IOException; import org.springframework.util.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; 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; } } }

package net.xdclass.base_project.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; /** * 功能描述:redis工具類 * * <p> 創建時間:Apr 29, 2018 10:07:30 PM </p> * *@作者 小D課堂 小D */ @Component public class RedisClient { @Autowired private StringRedisTemplate redisTpl; //jdbcTemplate /** * 功能描述:設置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){ return redisTpl.opsForValue().get(key); } // @Autowired // private StringRedisTemplate redisTemplate; // // // /** // * 通過字符串key獲取值 // * @param key 鍵 // * @return 值 // */ // public String get(String key){ // return key==null?null:redisTemplate.opsForValue().get(key); // } // // // /** // * 普通緩存放入 // * @param key 鍵 // * @param value 值 // * @return true成功 false失敗 // */ // public boolean set(String key,String value) { // try { // redisTemplate.opsForValue().set(key, value); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // // } // // // /** // * 功能描述:設置某個key過期時間 // * @param key // * @param time // * @return // */ // public boolean expire(String key,long time){ // try { // if(time>0){ // redisTemplate.expire(key, time, TimeUnit.SECONDS); // } // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // // // // /** // * 功能描述:根據key 獲取過期時間 // * @param key // * @return // */ // public long getExpire(String key){ // return redisTemplate.getExpire(key,TimeUnit.SECONDS); // } // // // /** // * 遞增 // * @param key 鍵 // * @return // */ // public long incr(String key, long delta){ // return redisTemplate.opsForValue().increment(key, delta); // } // // // /** // * 遞減 // * @param key 鍵 // * @param delta 要減少幾 // * @return // */ // public long decr(String key, long delta){ // return redisTemplate.opsForValue().increment(key, -delta); // } // // //==============Map結構===================== // // // //==============List結構===================== // // // }

package net.xdclass.base_project.controller; import java.util.Date; import net.xdclass.base_project.domain.JsonData; import net.xdclass.base_project.domain.User; import net.xdclass.base_project.utils.JsonUtils; import net.xdclass.base_project.utils.RedisClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/redis") public class RdisTestController { @Autowired private StringRedisTemplate redisTpl; //jdbcTemplate @Autowired private RedisClient redis; @GetMapping(value="add") public Object add(){ //redisTpl.opsForValue().set("name", "xdclass2018"); redis.set("username", "xddddddd"); return JsonData.buildSuccess(); } @GetMapping(value="get") public Object get(){ //String value = redisTpl.opsForValue().get("name"); String value = redis.get("username"); return JsonData.buildSuccess(value); } @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); } @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); } }
test單元測試

package base_project.base; import net.xdclass.base_project.XdclassApplication; import net.xdclass.base_project.domain.User; import net.xdclass.base_project.utils.JsonUtils; import net.xdclass.base_project.utils.RedisClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner @SpringBootTest(classes={XdclassApplication.class})//啟動整個springboot工程 public class JsonTest { @Autowired private StringRedisTemplate strTpl; @Autowired private RedisClient redis; @Test public void testOne(){ User u = new User(); u.setAge(1); u.setPhone("22222"); u.setPwd("0000"); String str = JsonUtils.obj2String(u); strTpl.opsForValue().set("str", str); System.out.println(str); } }