Spring integration redis spring data redis

Keywords: Programming Redis Spring xml Jedis

Spring data redis encapsulates the operation of redis. It is very convenient to use redis in projects

Integrating spring data redis is very simple. There are three files that need to be modified. 1.pom.xml 2.application-context.xml 3.redis.properties

1. Add spring data redis and redis dependencies in pom

        <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 related configuration ps in spring configuration file: password is optional

    <bean id="jedisConnFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}"
          p:port="${redis.port}"
          p:password="${redis.auth}"
          p:use-pool="true"
    />
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connection-factory-ref="jedisConnFactory"/>

3. Create redis.properties configuration file

redis.host=localhost
redis.port=6379
redis.auth=123456

Now that we have finished the configuration, let's test it

@Slf4j
public class SpringDataRedisTest extends BaseAppTest {
  @Autowired
  private RedisTemplate redisTemplate;

  @Test
  public void testStringRedisTemplate() {
    ValueOperations<String, String> valueOpera = redisTemplate.opsForValue();
    valueOpera.set("name", "Zhang San");
    String name = valueOpera.get("name");
    assertEquals("Zhang San", name);
  }

  @Test
  public void testSetAndGet() {
    /*
    Based on the Ping API, we can encapsulate a tool class by ourselves, which is more convenient to use
     */
    RedisUtils.set("name", "Zhang San");
    String name = RedisUtils.get("name");
    assertEquals("Zhang San", name);
  }
}

The second method is the tool class encapsulated by itself, which is much easier to operate

Posted by big_al on Tue, 03 Dec 2019 05:17:41 -0800