Home  >  Article  >  Java  >  Detailed example of Spring integrating Redis based on annotations

Detailed example of Spring integrating Redis based on annotations

零下一度
零下一度Original
2017-07-19 13:45:531816browse

1. Add project dependencies

2. Add spring-redis-context configuration

3. Add redis.properties

4. Write a custom redis configuration class

5. Caching annotations where you like

As a memory-based Key-Value database, Redis is very cost-effective as a cache server.

The officially launched Client Jedis for Java provides many interfaces and methods to allow Java operations to use Redis.

The Spring team has encapsulated Jedis as an independent spring-data-redis project, matching spring features and integrating some commands and methods of Jedis.

This article focuses on describing the integration process, which allows you to quickly integrate redis into the spring project through spring-data-redis. After all, everyone is busy.

This article focuses on describing the integration process, which allows you to quickly integrate redis into the spring project through spring-data-redis. After all, everyone is busy.

1. Add project dependencies

        <!--redis 缓存--><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.8.4.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency>

2. Add spring-redis-context configuration

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:context="http://www.springframework.org/schema/context"   xsi:schemaLocation="http://www.springframework.org/schema/beans
                        
                        
                        "><description>redis 相关类 Spring 托管</description><!--载入 redis 配置文件--><context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/><!-- 配置 JedisPoolConfig 实例 --><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}"/><property name="maxTotal" value="${redis.maxActive}"/><property name="maxWaitMillis" value="${redis.maxWait}"/><property name="testOnBorrow" value="${redis.testOnBorrow}"/></bean><!-- 配置JedisConnectionFactory --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="hostName" value="${redis.host}"/><property name="port" value="${redis.port}"/><property name="password" value="${redis.pass}"/><property name="database" value="${redis.dbIndex}"/><property name="poolConfig" ref="poolConfig"/></bean><!-- 配置RedisTemplate --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="jedisConnectionFactory"/></bean><!-- 配置RedisCacheManager --><bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"><constructor-arg name="redisOperations" ref="redisTemplate"/><property name="defaultExpiration" value="${redis.expiration}"/></bean><!-- 配置RedisCacheConfig --><bean id="redisCacheConfig" class="com.rambo.sdh.common.util.RedisCacheConfig"><constructor-arg ref="jedisConnectionFactory"/><constructor-arg ref="redisTemplate"/><constructor-arg ref="redisCacheManager"/></bean></beans>

JedisConnectionFactory is the Jedis connection factory, and the configuration is provided by a separate abstract JedisPoolConfig.

If you are familiar with Spring's JdbcTemplate object, you can probably guess the role of RedisTemplate, RedisTemplate is correct RedisConnection is encapsulated.

Provides connection management, serialization and other functions. It provides a higher level of abstraction for Redis interaction, which greatly facilitates and simplifies the operation of Redis.

RedisCacheManager As the unified scheduler and manager of redis, if you are interested, you can decompile the source code and take a look.

Inherits from org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager and implements org.springframework.cache.CacheManager.

3. Add redis.properties

#============================#
#==== Redis settings ====#
#============================#
#redis 服务器 IP
redis.host=127.0.0.1

#redis 服务器端口
redis.port=6379

#redis 密码
redis.pass=redis#2017

#redis 支持16个数据库(相当于不同用户)可以使不同的应用程序数据彼此分开同时又存储在相同的实例上
redis.dbIndex=0

#redis 缓存数据过期时间单位秒
redis.expiration=3000

#控制一个 pool 最多有多少个状态为 idle 的jedis实例
redis.maxIdle=300

#控制一个 pool 可分配多少个jedis实例
redis.maxActive=600

#当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
redis.maxWait=1000

#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true

Of course, you can also hardcode the configuration file into the program, just when the parameters occur It's just a little more painful when changing.

Most of the configuration items are around jedisPool. If you are familiar with database connection pools, you will find that their configuration items are somewhat similar.

When the system redis encounters a problem and fails, it is a good choice to understand the options here. More configuration items are explained in detail.

4. Write a custom redis configuration class

@Configuration
@EnableCachingpublic class RedisCacheConfig extends CachingConfigurerSupport {protected final static Logger log = LoggerFactory.getLogger(RedisCacheConfig.class);private volatile JedisConnectionFactory mJedisConnectionFactory;private volatile RedisTemplate<String, String> mRedisTemplate;private volatile RedisCacheManager mRedisCacheManager;public RedisCacheConfig() {super();
    }public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate<String, String> mRedisTemplate, RedisCacheManager mRedisCacheManager) {super();this.mJedisConnectionFactory = mJedisConnectionFactory;this.mRedisTemplate = mRedisTemplate;this.mRedisCacheManager = mRedisCacheManager;
    }public JedisConnectionFactory redisConnectionFactory() {return mJedisConnectionFactory;
    }public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {return mRedisTemplate;
    }public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {return mRedisCacheManager;
    }

    @Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {
            @Overridepublic Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());for (Object obj : objects) {
                    sb.append(obj.toString());
                }return sb.toString();
            }
        };
    }
}

This configuration class inherits from org.springframework.cache.annotation.CachingConfigurerSupport and implements the methods of org.springframework.cache.annotation.CachingConfigurer.

In layman's terms, this class tells spring that the cache service currently used is redis and customizes the rules for cache key generation.

5. Cache annotations where you like

Cache Generally used in the service layer, just add the corresponding annotations to the method you want to cache. You must master the following three caching annotations.

@Cacheable spring will cache the return value after it is called to ensure that the next time the method is executed with the same parameters, the result can be obtained directly from the cache without The method needs to be executed again.

The @CachePut annotated method will not check whether there are previously executed results in the cache before execution. Instead, the method will be executed every time and the execution results will be expressed as key values. The correct form is stored in the specified cache.

@CacheEvict is used to annotate methods or classes that need to clear cache elements.

Of course, there are many other attribute configurations in these annotations, and there are many things that can be done with spring-el expressions. It is probably only your imagination, but there is nothing that cannot be done.

When the business rules are complex, the design of the cache key is very important. Excellent design can make your application fly.

The above is the detailed content of Detailed example of Spring integrating Redis based on annotations. 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