Reids (1) Redis and Mybatis realize distributed caching

Distributed cache

  • The connection between Java and Mysql database is the time when efficiency is most affected. Frequent database queries will slow down the system's response. In the interaction with the database, most of the work is used for querying. Returning Mysql data query results to the background is equivalent to reading the data in the hard disk into the memory, which affects the query efficiency. Put the data to be queried into the cache, and when querying again, it will no longer go to the database, but go directly to the memory to get it.

  • Putting it directly in a memory with the program will also affect the runtime resources of the program. It is also because different services cannot directly share the cache, so the distributed cache is used. The combination of Redis as an excellent memory-based NoSql and Mybatis second-level cache can effectively solve the problem.

0, open the print SQL statement

logging.level.com.wdd.dao=debug

1. Entity class (database)

Java needs to be serialized into Redis.

@Data
public class Emp implements Serializable {
    
    
    private String id;
    private String name;
    private String path;
    private Double salary;
    private String age;
}

2、mapper.xml

<mapper namespace="com.wdd.dao.EmpDao">
	<!--查询所有  -->
    <select id="findAll"  resultType="Emp">
        select id,name,path,salary,age from t_emp
    </select>
	<!-- 插入数据 -->
    <insert id="save" parameterType="Emp" useGeneratedKeys="true" keyProperty="id">
        insert into t_emp value (#{id},#{name},#{path},#{salary},#{age})
    </insert>
</mapper>

3. Test query

  • Every time a findAll() request is sent, the sql execution statement will be printed on the console

4. Introduce Redis to implement the Cache interface ( org.apache.ibatis.cache.Cachepackage)

public class RedisCache implements Cache {
    
    

    //存入缓存需要一个id,实际上是mapper.xml中的namespace
    private String id;

    //写出有参构造,为了Mybatis实现
    public RedisCache(String id) {
    
    
        this.id = id;
    }
    
    //私有方法用于本类中调用
     private RedisTemplate<Object,Object> getRedisTemplate(){
    
    
        RedisTemplate<Object,Object> redisTemplate = (RedisTemplate) AppUtils.getBean("redisTemplate");
         //key的序列化策略为String类型序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
         //Hashkey的序列化策略为String类型序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        
        return redisTemplate;
    }

    @Override
    public String getId() {
    
    
        return this.id;
    }

    @Override//放入缓存,存入Hash结构中,id为namespace,Hashkey为sql语句,hashvalue为查询结果
    public void putObject(Object key, Object value) {
    
    
        getRedisTemplate().opsForHash().put(id, key.toString(), value);
    }

    @Override//取出缓存,若两次查询sql语句一致,直接从缓存中给出数值
    public Object getObject(Object key) {
    
    
        return getRedisTemplate().opsForHash().get(id,key.toString());
    }

    @Override//删除指定缓存信息,未实现
    public Object removeObject(Object key) {
    
    
        return null;
    }

    //清除缓存,在进行增,删,改时会清空namespace的缓存,直接删除hash结构,也会删除关联此namespace的缓存
    @Override
    public void clear() {
    
    
        getRedisTemplate().opsForHash().delete(id);
    }

    @Override
    public int getSize() {
    
    
        return getRedisTemplate().opsForHash().size(id).intValue();
    }
}

5. Get the Bean tool class

@Component
public class AppUtils implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext;
   
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.applicationContext = applicationContext;
    }

    public static Object getBean(String  name){
    
    
        return applicationContext.getBean(name);
    }
}

6. Use cache

<mapper namespace="com.wdd.dao.EmpDao">
    <cache type="com.wdd.cache.RedisCache"/>
   			......
</mapper>

7. Test

  • The findAll() request will go to Mysql for the first time and store the result in Redis. The second time it hits the cache, the query data will be returned directly;
  • save() requests to go to the database, change the database data, and clear the data in Redis;
  • Requesting findAll() again will request the database and re-store it in Redis

Guess you like

Origin blog.csdn.net/qq_38473355/article/details/108747044