SpringBoot-- integrated Redis

pom.xml jar package is introduced, as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Modify the project startup class, increase annotation @EnableCaching, open the cache function, as follows:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EnableCaching
public class SpringbootApplication{

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

application.properties Redis connection configuration information as follows:

# Redis database indexes (default is 0)
spring.redis.database=0
# Redis server address
spring.redis.host=172.31.19.222
# Redis server connection port
spring.redis.port=6379
# Redis server connection password (default is empty)
spring.redis.password=
# Connection pool maximum number of connections (use a negative value means no limit)
spring.redis.pool.max-active=8
# Connection pool maximum block waiting time (use a negative value means no limit)
spring.redis.pool.max-wait=-1
# Maximum connection pool idle connections
spring.redis.pool.max-idle=8
# The minimum connection pool idle connections
spring.redis.pool.min-idle=0
# Connection time (ms)
spring.redis.timeout=0

New classes Redis cache configuration RedisConfig, as follows:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * Redis cache configuration class
 * @author szekinwin
 *
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    
    //自定义缓存key生成策略
//    @Bean
//    public KeyGenerator keyGenerator() {
//        return new KeyGenerator(){
//            @Override
//            public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
//                StringBuffer sb = new StringBuffer();
//                sb.append(target.getClass().getName());
//                sb.append(method.getName());
//                for(Object obj:params){
//                    sb.append(obj.toString());
//                }
//                sb.toString return ();
 //             }
 //         };
 //     }
     // cache manager 
    @Bean 
     public the CacheManager CacheManager (@SuppressWarnings ( "rawtypes" ) RedisTemplate redisTemplate) {
        CacheManager RedisCacheManager = new new RedisCacheManager (redisTemplate);
         // set the cache expiration time 
        cacheManager.setDefaultExpiration (10000 );
         return CacheManager;
    }
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer (Template); // Set the serial tool 
        template.afterPropertiesSet ();
         return Template;
    }
     private void setSerializer(StringRedisTemplate template){
            @SuppressWarnings({ "rawtypes", "unchecked" })
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            template.setValueSerializer(jackson2JsonRedisSerializer);
     }
}

New UserMapper, as follows:

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import springboot.domain.User;

@Mapper
@CacheConfig(cacheNames = "users")
public interface UserMapper {

    @Insert("insert into user(name,age) values(#{name},#{age})")
    int addUser(@Param("name")String name,@Param("age")String age);
    
    @Select("select * from user where id =#{id}")
    @Cacheable(key ="#p0") 
    User findById(@Param("id") String id);
    
    @CachePut(key = "#p0")
    @Update("update user set name=#{name} where id=#{id}")
    void updataById(@Param("id")String id,@Param("name")String name);
    
    // If you specify true, the method call will immediately clear all cache 
    @CacheEvict (Key = "# P0", allEntries = to true )
    @Delete("delete from user where id=#{id}")
    void deleteById(@Param("id")String id);
    
}

@Cacheable query results in the cache to redis, (key = "# p0") to specify the first argument as a key redis.

  @CachePut, specify the key, the updated results in sync to redis

  @CacheEvict, specify the key, delete cache data, allEntries = true, clear the cache immediately after the method call

  (6) service layer and controller layer to keep up with an integrated, like, start redis server, before the redis server installation and startup blog can refer to the following address:

    http://www.cnblogs.com/gdpuzxs/p/6623171.html

  (7) configure log4j log, as follows:

## LOG4J Configuration
log4j.rootCategory=DEBUG,stdout
## console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

Cache verification redis

  First, we always insert a data table to the user, the database appears as follows:

  

  Now, we check what data the user table id = 24, the console output view rub, as follows:

  

  The console output, we know that the implementation of a database query, and opened Redis caching query results. Next we again query the data in the user table id = 24 observed the console, as follows:

  

  By console output information we can know that this did not execute database queries, but the query from Redis cache, and returns the query results. We view the information redis, as follows:

  

  Methods finduser method uses annotations @Cacheable (key = "# p0"), is about to id as key values ​​in redis. When we update the data should be used @CachePut (key = "# p0") to update cached data, otherwise it will query the dirty data.

Guess you like

Origin www.cnblogs.com/jvStarBlog/p/11819434.html