Redis serves as a memory-based Key-Value database and has a high cost-effective performance as a cache server.
The official Java-oriented Client Jedis provides many interfaces and methods for Java operations to use Redis.
The Spring team encapsulated Jedis independently as a spring-data-redis project, cooperating with spring features and integrating some commands and methods of Jedis.
This article focuses on the integration process, allowing you to quickly integrate redis into spring projects through spring-data-redis, after all, everyone is busy.
"I am an old programmer, resigning as a lecturer, and this year I have sorted out a JAVA dry product suitable for learning in 2019, from the most basic object-oriented to a variety of frameworks, for every junior and advanced buddy who wants to learn J a v a programming. "
QQ Junyang: 69769, 9179 (Recruitment)
1. Adding project dependencies
<!--redis cache--> <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 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <description>redis Related classes Spring Trusteeship</description> <!--load redis configuration file--> <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/> <!-- To configure JedisPoolConfig Example --> <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> <!-- To configure 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> <!-- To configure RedisTemplate --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> </bean> <!-- To configure RedisCacheManager --> <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg name="redisOperations" ref="redisTemplate"/> <property name="defaultExpiration" value="${redis.expiration}"/> </bean> <!-- To configure 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>
Jedis Connection Factory is the Jedis Connection Factory, and the configuration is provided by a separate Abstract Jedis Pool Config.
If you are familiar with Spring's JdbcTemplate object, you can probably guess the role of RedisTemplate, which encapsulates RedisConnection.
It provides connection management, serialization and other functions. It abstracts the interaction of Redis at a higher level, which greatly facilitates and simplifies the operation of Redis.
RedisCache Manager, as a unified dispatcher and manager of redis, is interested in decompiling the source code.
Inherit from org. spring framework. cache. transaction. AbstractTransaction Supporting Cache Manager and implement org. spring framework. cache. Cache Manager.
3. Add redis.properties
#============================# #==== Redis settings ====# #============================# #redis server IP redis.host=127.0.0.1 #redis server port redis.port=6379 #redis password redis.pass=redis#2017 #redis supports 16 databases (equivalent to different users) that allow different application data to be separated from each other and stored on the same instance redis.dbIndex=0 #redis cache data expiration time unit seconds redis.expiration=3000 #Controlling the maximum number of jedis instances of a pool with idle status redis.maxIdle=300 #Control how many jedis instances a pool can allocate redis.maxActive=600 #When borrow a jedis instance, the maximum waiting time, if it exceeds the waiting time, throws JedisConnectionException directly. redis.maxWait=1000 #When borrow ing a jedis instance, do you alidate ahead of time? If true, all the jedis instances are available. redis.testOnBorrow=true
Of course, configuration files can also be hard-coded into the program, just when the parameters change a little more painful.
Most of the configuration items are around jedisPool. If you are familiar with database connection pools, you will find that they are similar.
Understanding the options here is a good choice when system redis fails.
4. Write a custom redis configuration class
@Configuration @EnableCaching public 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; } @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public 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. spring framework. cache. annotation. CachingConfigurerSupport and implements the method of org. spring framework. cache. annotation. CachingConfigurer.
Popularly, this class tells spring that the caching service currently in use is redis and customizes the rules for caching key generation.
5. Caching annotations where you like
Caching is usually used in the service layer. You can add the corresponding annotations to the method you want to cache. The following three caching annotations you need to master.
- @ Cacheable spring caches the return value after it is invoked to ensure that the next time the same parameter is used to execute the method, the result can be obtained directly from the cache without requiring the method to be executed again.
- @ The CachePut annotation method does not check the existence of previously executed results in the cache before execution. Instead, it executes the method every time and stores the execution results in the specified cache in the form of key-value pairs.
- @ CacheEvict is used to annotate methods or classes that need to clear cached elements.
- Of course, there are many other attribute configurations in these annotations, and there are many things you can do with spring-el expressions, probably only you can't imagine, not do it.
In the case of complex business rules, the design of caching key is very important. Excellent design can make your application fly.
The whole integration work is over. Is it simple? The above is the tip of redis'iceberg, and there are many other things like redis routing / distributed / clustering? Have the opportunity to practice slowly.
"I am an old programmer, resigning as a lecturer, and this year I have sorted out a JAVA dry product suitable for learning in 2019, from the most basic object-oriented to a variety of frameworks, for every junior and advanced buddy who wants to learn J a v a programming. "
QQ Junyang: 69769, 9179 (Recruitment)