非關系型資料庫NOSQL Redis
- NOSQL介紹
- 關系型資料庫和非關系型資料庫的區別
- 關系型資料庫(Mysql Oracle SqlServer)
- 非關系型資料庫(NOSQL)
- Redis的介紹
- 使用Redis的好處
- 應用場景
- Redis使用
- redis服務器
- 打開redis圖形化工具
- JedisUtil工具讀寫資料
- jedis.properties
- CategoryServlet使用redis
NOSQL介紹
(1)什么是NOSQL
NoSQL(NoSQL = Not Only SQL),意即“不僅僅是SQL”,是一項全新的資料庫理念,泛指非關系型的資料庫
NOSQL是非關系型資料庫
Redis: 就是NOSQL 非關系型資料庫
MySql Oracle :關系型資料庫
關系型資料庫和非關系型資料庫的區別
關系型資料庫(Mysql Oracle SqlServer)
1:資料是由一張張的表組成,而且這些表與表之間有關系(一對一,一對多,多對多)
2:資料是存在硬碟上,每次訪問時,是將資料從硬碟讀取到記憶體中

非關系型資料庫(NOSQL)
》1: 資料是有一個個的鍵值對:鍵 值
》2:資料是存在記憶體中,在滿足需要的時候,也可以將資料存在硬碟上(Redis的持久化)

Redis的介紹
Redis(Remote Dictionary Server ) 遠程字典服務,是一個非關系型資料庫
使用Redis的好處
每一次頁面加載后都會重新請求資料庫來加載,對資料庫的壓力比較大,而且分類的資料不會經常產生變化,所有可以使用redis來快取這個資料,

應用場景
Redis一般用來存盤經常訪問的,但有不經常改變的資料
- 快取 處理一些臨時資料
- 聊天室的在線好友串列
- 網站訪問統計
Redis使用
雖然 訪問redis 較快,但是第一次是沒有資料的
訪問service,獲取json,將json保存到redis
redis服務器
打開start.bat,打開服務器

打開redis圖形化工具

JedisUtil工具讀寫資料
package com.wzx.lvyou.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Jedis工具類
*/
public final class JedisUtil {
private static JedisPool jedisPool;
static {
//讀取組態檔
InputStream is = JedisPool.class.getClassLoader().getResourceAsStream("jedis.properties");
//創建Properties物件
Properties pro = new Properties();
//關聯檔案
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//獲取資料,設定到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
//初始化JedisPool
jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
/**
* 獲取連接方法
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
/**
* 關閉Jedis
*/
public static void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
jedis.properties
host=192.168.21.101
port=6379
maxTotal=100 //最大連接數
maxIdle=10 //最大空閑數
CategoryServlet使用redis
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//訪問service,獲取json,將json保存到redis
Jedis jedis = JedisUtil.getJedis();
String json = jedis.get("category_list");
if (json != null) {
System.out.println("redis cache");
response.getWriter().println(json);
} else { //訪問redis 較快,但是第一次是沒有資料的,所以訪問資料庫
System.out.println("mysql data");
//創建業務物件
CategoryService categoryService = new CategoryService();
//所有的分類
List<Category> categoryList=categoryService.findAll();
//顯示
ResponseInfo info = new ResponseInfo();
info.setCode(200);
info.setData(categoryList);
json = new ObjectMapper().writeValueAsString(info);
//將資料保存到redis
jedis.set("category_list",json);
response.getWriter().println(json);
}
//關閉連接
JedisUtil.close(jedis);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/189784.html
標籤:其他
