Jedis is a java client that connects to redis. Spring is encapsulated based on jedis and provides a concise method of operating redis.
Use maven to manage dependencies between jar packages:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis-version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${redis.clients-jedis-version}</version> </dependency>spring-data-redis needs to depend on the jedis package. In fact, the jedis configuration is automatically included in the spring-data-redis pom file. http://www.mvnrepository.com/ depending on the version required.
(1), JedisConnectionFactory redis connection factory
Similar to the database connection pool, the redis client also establishes a connection factory
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory connFactory = new JedisConnectionFactory(); connFactory.setHostName("127.0.0.1"); connFactory.setPort(6379); connFactory.setUsePool(true);//Use connection pool return connFactory; }(2)、redis RedisTemplate
With the redis connection factory, a specific redis session is required. These are all the same reasons.
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Bean public RedisTemplate<String, String> redis() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer());//Key serialization adapter redisTemplate.setValueSerializer(new StringRedisSerializer());//The serialization adapter for value can also be written by yourself. StringRedisSerializer is sufficient for most scenarios. return redisTemplate; }
(3), everything is ready, start to operate redis
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class CacheDemo { @Autowired private RedisTemplate<String, String> redis; public void set(String key,String value){ redis.opsForValue().set(key, value); } }
(4), summary.
It would be nice if everything were as simple as this, but spring has been packaged extremely concisely and very easy to operate.
redis.opsForValue() encapsulates operation strings
redis.opsForList() encapsulates the operation list
redis.opsForSet() encapsulates operation sets
redis.opsForZSet() encapsulates the operation sorted sets
redis.opsForHash() encapsulates operation hashs
Keep digging for other things.