Do you know how to use it in redis in springboot

Tales of Vesperia

Special note : This article is directed to the new spring boot 2.1.3, which spring data dependency is spring-boot-starter-data- redis, and the default connection pool lettuce

redis as a high-performance memory database, if you do not use too outdated, used before in redis in node.js herein, this record redis how to integrate into spring boot in. Providing redis action class, and use the annotation redis two ways. The main contents are as follows:

  • docker install redis
  • springboot integration redis
  • Redis write operation class
  • By using annotations redis

Install redis

  By mounting docker, docker compose documents organized as follows:

# docker-compose.yml
version: "2"
services:
  redis:
    container_name: redis
    image: redis:3.2.10
    ports:
      - "6379:6379"

  Then docker-compose.ymluse the directory docker-compose up -dcommand to start redis.

Integrated springboot

  Description: springboot version 2.1.3

Add maven dependence

  Just add spring-boot-starter-data-redisdependency to, and dependent on lettuce excluded, and then introduced jedis jedis dependent commons-pool2

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

Write springboot profile

  Configuration files are as follows:

server:
  port: 8081
  servlet:
    context-path: /sso
spring:
  application:
    name: SSO
  cache:
    type: redis
  redis:
    database: 0
    host: 192.168.226.5
    port: 6379
    # 有密码填密码,没有密码不填
    password:
    # 连接超时时间(ms)
    timeout: 1000ms
    # 高版本springboot中使用jedis或者lettuce
    jedis:
      pool:
        # 连接池最大连接数(负值表示无限制)
        max-active: 8
        # 连接池最大阻塞等待时间(负值无限制)
        max-wait: 5000ms
        # 最大空闲链接数
        max-idle: 8
        # 最小空闲链接数
        min-idle: 0

Write configuration class

  Configuration class code as follows:

@EnableCaching//开启缓存
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 设置缓存管理器,这里可以配置默认过期时间等
     *
     * @param connectionFactory 连接池
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60));
        //注意:请勿使用先new 配置对象,然后在调用entryTtl方法的方式来操作
        //会导致配置不生效,原因是调用.entryTtl方法会返回一个新的配置对象,而不是在原来的配置对象上修改

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
        return manager;
    }

    @SuppressWarnings("all")
    @Bean
    public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        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);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    //使用jedis连接池建立jedis连接工厂
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        logger.info("jedisConnectionFactory:初始化了");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxTotal(maxActive);
        //链接耗尽时是否阻塞,默认true
        config.setBlockWhenExhausted(true);
        //是否启用pool的jmx管理功能,默认true
        config.setJmxEnabled(true);
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setPoolConfig(config);
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setDatabase(database);
        factory.setTimeout(timeout);
        return factory;
    }
}

Instructions

  There are two ways to cache operation, it is to add annotations in the cache method to implement various operations, one is a manual control. Personally prefer manual control, I feel so in control of his own.

By using annotations

  Mainly in the following five notes:

  • @CacheConfig: Class-level caching, set the cache key prefix like
  • @Cacheable: Trigger cache entry
  • @CacheEvict: Trigger remove cache
  • @CachePut: refresh cache
  • @Caching: A combination of caching

@CacheConfig

  The annotation can be cached classification, it is a class-level annotation, mainly for a class to cache global configuration examples are as follows:

@CacheConfig(cacheNames = "redis_test")
@Service
public class RedisService {
  //....
}

CacheConfig give the above categories annotation key generated by redis_test the prefix.

@Cacheable

  Method level annotations, according to key query cache:

  • If the key does not exist, the method returns a value in the cache to redis
  • If the key is present, the value directly from the cache
    examples are as follows:
    /**
     * 缓存时间,首次查询后会缓存结果,key中的值可使用表达式计算.
     * 如不提供key,将使用默认key构造方法生成一个key
     * @return long
     */
    @Cacheable(key = "'currentTime'")
    public long getTime() {
        return System.currentTimeMillis();
    }

Multiple calls this code will find that the value returned is the same every time.

CachePut

  For updating the cache, each call will want to request db, cache data

  • If the key exists, updates
  • If the key does not exist, insert content

code show as below:

/**
     * 一般用于更新查插入操作,每次都会请求db
     */
    @CachePut(key = "'currentTime'+#id")
    public long updateTime(String id) {
        return System.currentTimeMillis();
    }

This method will cache data in accordance with key redis refresh call.

@CacheEvict

  According to the data key to delete the cache. allEntries = true means to delete all the data in the cache.
code show as below:

    @CacheEvict(key = "'currentTime'+#id",allEntries=false)
    public void deleteTime(String id) {
    }

@Caching

  This annotation can be used in combination other annotations. Such as the following examples:

    //value属性为key指定前缀
    @Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"),
            @CachePut(value = "user", key = "'pass_'+#user.password")})
    public User testCaching(User user) {
        return user;
    }

After performing the above code is inserted in the two records in redis. Use keys *will see the following results:

result

Manual control

  Manual control is equivalent mybatis handwritten sql statements need to call redisTemplatein a variety of ways to cache query cache update, delete the cache and other operations.

  Use see methods util / RedisUtil in. redisTemplateCan be achieved basically all redis operations.

Benpian Original Posted: springboot integration redis

Project Source: : GitHub

Guess you like

Origin www.cnblogs.com/wuyoucao/p/10941792.html