[Redis1] Common operations, persistence, Jedis


1. Installation: load .conf

WeChat Moments data is cached in the phone's memory, and a large number of video bullets, that is, massive data, is cached and then written to a relational database. The following storage files are not available for the first use. The blue horizontal line below is a shortcut and the .conf file is added at the end. Mysql defaults to port 3306, and tomcat defaults to port 8080. The redis-cli.exe command line client is not easy to use, use a graphical client.
Insert picture description here
Nosql products are as follows. The disadvantage of Redis is that there are 5 types of value and no fixed structure. HBase distributed like binary tree query efficiency is high, data is constantly added, so it has strong scalability. MongoDB is like a grocery bag, and there is no need to separate them into categories.
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

2. Common operations: set/get, push/pop, add/rem

Insert picture description here
Insert picture description here
Insert picture description here
Because the elements are not repeated, they can be disordered. Reorder the order.
Insert picture description here
Insert picture description here
Understand that score is a repeatable score.
Insert picture description here
Insert picture description here

3. Persistence strategy: If the .aof and .rdb files are deleted, the data in the database is gone

In the following RDB, 900 seconds is 15 minutes. For example, if you operate 2 times in 0-15 minutes, take a photo to save the hard disk. However, it was operated twice in 15-27 minutes (only in accordance with the save 900 1 strategy). At this time, redis crashed, and it took 15-30 minutes to take pictures and save, so 2 pieces of data were lost. Therefore, infrequent operations will lose data.

In the following AOF, writing a log is not to record the entire photo, but to record one step (faster to save), so 读取慢因为要从头看到尾that the entire process can be linked. AOF只能三者选其一,不像RDB三个策略都在线(默认开启),AOF是RDB(会丢数据)的补丁. Modify appendonly to yes in redis_windows.conf, so the redis_windows.conf file name was added to the shortcut target before.

Scenario: 2000 times every 10 seconds (total 8*2000=16000 times), 12000 times per minute 60 seconds (At this time, RDB takes a photo, and there is not time to take 20 seconds, because too often the photo will be stuck). Why use RDB first? Because the reading is fast.
Insert picture description here
Insert picture description here

4. Jedis: java program connects redis, ResourceBundle.getBundle

Insert picture description here

package com.itheima01.jedis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisDemo {
    
       
    @Test
    public void method01(){
    
           
        String host = "127.0.0.1"; 
        int port = 6379;
        Jedis jedis = new Jedis(host, port);  //1. 创建连接,不用连接池       
        jedis.set("book","thinking");   //2. 访问redis
        jedis.hset("student","name","zs");        
        jedis.close();  //3. 关闭连接
        System.out.println("测试");
   }
    @Test
    public void method02(){
    
           
        String host = "127.0.0.1";
        int port = 6379;
        JedisPoolConfig config = new JedisPoolConfig(); //连接池
        config.setMaxTotal(5); //最大连接数
        config.setMaxWaitMillis(2000); // 最长等待时间
        config.setMaxIdle(2); // 最大空闲数:最多允许两个连接不干活,超过两个会被回收掉,达到释放内存目的
        
        JedisPool pool = new JedisPool(config, host, port); //1. 初始化连接池        
        Jedis jedis = pool.getResource(); //2. 获取连接        
        String book = jedis.get("book"); //3. 访问redis
        System.out.println(book);  //thinking      
        jedis.close();  //4. 将连接还给连接池
        pool.close(); // 销毁连接池,一般只有应用关闭时才用
    }
    @Test
    public void method03(){
    
     //测试封装的框架
        Jedis jedis = JedisUtil.getResource();
        String book = jedis.get("book");
        System.out.println(book + "-------");
        jedis.close();
    }
}
package com.itheima01.jedis;
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;
import java.util.ResourceBundle;

public class JedisUtil {
    
    
    private static JedisPool pool;
   /* static{
        String host = "127.0.0.1";
        int port = 6379;
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(5);  //最大连接数
        config.setMaxWaitMillis(2000);  // 最长等待时间
        config.setMaxIdle(2);  // 最大空闲数
        pool = new JedisPool(config, host, port);
    }*/
    
	//如下可替代如上 
    /*static{
        Properties p = new Properties();
        InputStream is = JedisUtil.class.getClassLoader().getResourceAsStream("jedis.properties");
        try {
            p.load(is);
            String host = p.getProperty("host");
            Integer port = Integer.parseInt(p.getProperty("port"));
            Integer maxTotal = Integer.parseInt(p.getProperty("maxTotal"));
            Integer maxWaitMillis = Integer.parseInt(p.getProperty("maxWaitMillis"));
            Integer maxIdle = Integer.parseInt(p.getProperty("maxIdle"));
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(maxTotal); //最大连接数
            config.setMaxWaitMillis(maxWaitMillis); // 最长等待时间
            config.setMaxIdle(maxIdle); // 最大空闲数
            pool = new JedisPool(config, host, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    
    //如下可替代如上 
    static{
    
    
        /*
        * ResourceBundle : 资源堆
        *    1. 底层: 类加载器  -> 文件必须放在src下
        *    2. 只能加载properties文件 -> 文件的后缀名.properties不要写。
        *       用来替代Properties成为 properties文件专属解析类
        * */
        ResourceBundle bundle = ResourceBundle.getBundle("jedis");
        String host = bundle.getString("host");
        Integer port = Integer.parseInt(bundle.getString("port"));
        Integer maxTotal = Integer.parseInt(bundle.getString("maxTotal"));
        Integer maxWaitMillis = Integer.parseInt(bundle.getString("maxWaitMillis"));
        Integer maxIdle = Integer.parseInt(bundle.getString("maxIdle"));
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal); //最大连接数
        config.setMaxWaitMillis(maxWaitMillis); // 最长等待时间
        config.setMaxIdle(maxIdle); // 最大空闲数
        pool = new JedisPool(config, host, port);
    }
    public static Jedis getResource(){
    
    
        Jedis jedis = pool.getResource();
        return jedis;
    }
}
//jedis.properties文件 
host = 127.0.0.1
port = 6379
maxTotal = 5
maxWaitMillis = 2000
maxIdle = 2

5. Case_Friend List: json = om.

Insert picture description here
Insert picture description here
Insert picture description here

//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
     
      //页面加载事件
            $.get("/FriendServlet","",function (data) {
     
      
                // console.log(data)
                var content = ""
                $(data).each(function (index,element) {
     
     
                    content += "<li>" + element.name + "</li>"
                })
                $("#myid").html(content) //因为<li>是html
            },"json")
        })
    </script>
</head>

<!--1111111111111111111111111111111111111111111111111111111111111111-->
<body>
        <ul id="myid">
        </ul>
</body>
</html>

Insert picture description here
Insert picture description here
Insert picture description here

package com.heima.example.web;
import com.heima.example.service.FriendService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/FriendServlet")
public class FriendServlet extends HttpServlet {
    
      
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        FriendService service = new FriendService(); //调用service层代码
        String json = service.findAllFriend();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(json);
    }
}
package com.heima.example.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.example.bean.Friend;
import com.heima.example.dao.FriendDao;
import com.itheima01.jedis.JedisUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import redis.clients.jedis.Jedis;
import java.util.List;
/*
*  service层: 业务逻辑 + 缓存 cache
*     弊端: 数据不更新 (查询走缓存, 如果执行增删查, 重新查询数据库,更新缓存)
*  如上括号里的解决方案也会存在缓存延迟的情况(如朋友圈删除动态有时也能看见)
*  朋友圈不是实时同步,如果实时同步对服务器来说压力大,好友列表的在线状态是实时同步的,用心跳长连接
*/
public class FriendService {
    
     //service文件夹下
    public static final String FRIEND_LIST_CACHE = "example_friend_list"; 
//选中再ctrl + shift + u转为大写,"example_friend_list"变量改了,下面FRIEND_LIST_CACHE常量不用改
    public String findAllFriend() throws JsonProcessingException {
    
            
        Jedis jedis = JedisUtil.getResource();
        String json = jedis.get(FRIEND_LIST_CACHE); //直接从缓存里取
        
        if(json == null){
    
     //就从mysql数据库中取                      
            FriendDao dao = new FriendDao();
            List<Friend> list = dao.findAll(); 
                        
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(list); //list转换为json            
            jedis.set(FRIEND_LIST_CACHE,json); //记得往缓存里放一份json即字符串
            System.out.println("从mysql中查");
        }else{
    
    
            System.out.println("从redis中查");
        }
        jedis.close(); //记得还给连接池,不然5个用完就崩了
        return json;
    }
}
package com.heima.example.dao;
import com.heima.example.bean.Friend;
import com.heima.example.utils.JdbcUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;

public class FriendDao {
    
      //Dao文件夹下
    public List<Friend> findAll() {
    
    
        String sql = "select * from user";
        JdbcTemplate template = JdbcUtil.getTemplate();
        List<Friend> list = template.query(sql, new BeanPropertyRowMapper<>(Friend.class));
        return list;
    }
}
package com.heima.example.bean;
 
public class Friend {
    
     //bean文件夹下
    private Integer id;
    private String name;
    private String password;
    @Override
    public String toString() {
    
    
        return "Friend{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }    
    public Integer getId() {
    
    
        return id;
    }    
    public void setId(Integer id) {
    
    
        this.id = id;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public String getPassword() {
    
    
        return password;
    }
    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

Insert picture description here
Insert picture description here
Station B/Zhihu/WeChat Official Account: Code Farming Programming Record
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43435675/article/details/108687436