Home  >  Article  >  Database  >  How to cache redis

How to cache redis

(*-*)浩
(*-*)浩Original
2019-11-20 11:31:193538browse

How to cache redis

#redis is often used as a cache server. The advantage of caching is that it reduces the pressure on the server and makes data query faster. Solve the problem of slow data response.

Add cache: Only add cache using the Hash data type of redis.                                                                                                                             (Recommended learning: Redis video tutorial)

For example: you need to add cache to the query business function

1.First you need to execute Before normal business logic (before querying the database), query the cache. If there is no required data in the cache, query the database

In order to prevent errors in adding cache and affecting the execution of normal business code, the Add cached code and place it in the try-catch code block so that the program can automatically capture it.

2. Complete the database query operation. After the query is completed, the queried data needs to be added to the cache.

Code:

@Override
    public List<TbContent> findContentByCategoryId(Long categoryId) {
        // 查询出的内容列表可以添加到缓存中,便于展示,为了保证添加缓存出现错误不影响程序的正常业务功能,可以使用try catch的方式加缓存
        try {
            String json = jedisClient.hget(CONTENT_LIST, categoryId + "");
            if (json != null) {
                List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        TbContentExample example = new TbContentExample();
        Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        // 使用selectByExampleWithBLOBs方法会将content属性框中的内容也查询出来
        List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);

        // 操作完成后需要将查询的内容添加到缓存中,因为添加缓存的过程可能出错,所以使用try catch将异常抛出即可
        // categoryId+""将Long类型的数据转换成String类型的
        try {
            jedisClient.hset(CONTENT_LIST, categoryId + "", JsonUtils.objectToJson(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

Json conversion tool class:

package nyist.e3.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 淘淘商城自定义响应结构
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
}

The above is the detailed content of How to cache redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn