Lxxxxxxy_
Lxxxxxxy_
Published on 2019-08-02 / 42 Visits
0

Redis的应用

Redis的应用

以前学了Redis,只是在linux里面使用了一下,没有通过代码来操作,今天试了一下Jedis来操作,就萌生了一个问题,Redis有什么用?

1、可以将数据库中查询到的数据以JSON方式存入Redis,等下次查询的时候就直接从Redis中取出(从内存中取出),减少CPU对硬盘的操作,从而提高效率,就不再从Mysql数据库中查询了。当然,这只是适用于Mysql中数据不常更新的。附上Demo

package cn.lixingyu.springredis.controller;

import cn.lixingyu.springredis.dao.RedisDao;
import cn.lixingyu.springredis.entity.Person;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @author lxxxxxxy
 * @time 2019/08/02 18:27
 */
@Controller
public class Jredis {

    private Jedis jedis;

    @Autowired
    private RedisDao redisDao;

    @GetMapping(value = "/getPerson")
    public String testJedis(Model model){
        //连接到Redis
        jedis = new Jedis("lixingyu.cn",6379);
        //判断Redis的personList的值是否为空,为空则存入,否则直接取出
        if(jedis.get("personList")==null){
            List<Person> personList = redisDao.getAllPerson();
            JSONArray jsonArray = JSONArray.fromObject(personList);
            String personListJson = jsonArray.toString();
            jedis.set("personList",personListJson);
        }
        String personList = jedis.get("personList");
        //将取出来的值存入Model
        model.addAttribute("personList",personList);
        return "index";
    }
}

2、接上一条,数据库中数据不常更新,可以在更新数据时,就把Redis中的键值删除,这样可以在下一次查询时,又从数据库中查找,存入Redis中。