Application scenarios:
The home page is visited by a large number of people every day, which causes great pressure to access the database, even paralysis.
So how to solve it? There are two ways we usually do this: one is data caching, the other is static web pages.
*** Four issues considered before using Redis? ***
1. Before querying the database, query whether there is cached data.
2. After querying the database, add the queried data to the cache.
3. Caching is only an optimization that does not affect normal business.
4. Cache synchronization should be considered when there is a cache, whether it is synchronized with the database or not.
1.Redis dependency import
<!-- cache --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency>
2. Configure redis-config.properties file
redis.host=127.0.0.1 redis.port=6379 redis.pass= redis.database=0 redis.maxIdle=300 redis.maxWait=3000 redis.testOnBorrow=true
3. Configure to create the application Context-redis.xml file
maxIdle: Maximum Free Number
maxWaitMillis: Maximum number of milliseconds to wait for a connection
TesOnBorrow: Whether to validate a jedis instance in advance when extracting it; if true, the resulting jedis instances are available;
<context:property-placeholder location="classpath*:properties/*.properties" /> <!-- redis Related configuration --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxWaitMillis" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="JedisConnectionFactory" /> </bean>
**
4. The service layer makes cache judgment.
**
@Autowired private TbContentMapper contentMapper; @Autowired private RedisTemplate redisTemplate; @Override public List<TbContent> findByCategoryId(Long categoryId) { //Query by Classified ID List<TbContent> list = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId); //If there is one in the cache, read the data directly from the cache if (list != null) { System.out.println("Query cache"); return list; } try { TbContentExample example = new TbContentExample(); Criteria criteria = example.createCriteria(); criteria.andCategoryIdEqualTo(categoryId); // Consistent with the ID criteria.andStatusEqualTo("1");// State 1 (valid) example.setOrderByClause("sort_order"); // Sort by ordinal number list = contentMapper.selectByExample(example); redisTemplate.boundHashOps("content").put(categoryId, list); System.out.println("query data base"); } catch (Exception e) { System.out.println("Query exception"); e.printStackTrace(); } return list; }
5. Update Cache
After adding, deleting and modifying, the cache should be cleared to realize immediate synchronization.
/** * increase */ @Override public void add(TbContent content) { contentMapper.insert(content); redisTemplate.boundHashOps("content").delete(content.getCategoryId()); } /** * modify */ @Override public void update(TbContent content) { // Query the original grouping ID Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId(); redisTemplate.boundHashOps("content").delete(categoryId ); contentMapper.updateByPrimaryKey(content); //If the ID after modification is different from the ID before modification, it is cleared again after modification. if(categoryId.longValue()!=content.getCategoryId().longValue()) { redisTemplate.boundHashOps("content").delete(content.getCategoryId()); } } /** * Batch deletion */ @Override public void delete(Long[] ids) { for (Long id : ids) { //Clear the cache before deleting redisTemplate.boundHashOps("content").delete(contentMapper.selectByPrimaryKey(id).getCategoryId()); contentMapper.deleteByPrimaryKey(id); } }