Spring下使用Redis

在Spring中使用Redis使用使用两个依赖包jedis.jar、spring-data-redis.jar

一下是Maven项目pom.xml添加依赖

<!--jedis.jar -->
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
  </dependency>

  <!-- Spring下使用Redis -->
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.2.RELEASE</version>
  </dependency>

要注意的是jar包和Spring版本的兼容性问题

笔者这里是使用注解方式进行配置

@Configuration
@ComponentScan("the_mass.redis")
public class SpringConfig {

    //Spring连接工厂
    @Bean
    RedisConnectionFactory redisFactory () {
        return new JedisConnectionFactory();
    }

    //反序列化
    @Bean
    RedisTemplate redisTemplate () {
        return new StringRedisTemplate(redisFactory());
    }
}

在JedisConnectionFactory可以设置许多参数的在此使用的是本机默认就好了

第二部服务层

package the_mass.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class RedisService {

    @Autowired
    RedisConnectionFactory factory;

    @Autowired
    RedisOperations redisOperations;

    public void testRedis() {
        RedisConnection connection = factory.getConnection();
        byte[] bytes = connection.get("hello".getBytes());
        System.out.println(new String(bytes, StandardCharsets.UTF_8));
    }

    public void testRedisTemplate () {
        Object hello = redisOperations.opsForValue().get("hello");
        System.out.println(hello);
    }
}

第三步

package the_mass.redis;

import redis.clients.jedis.Jedis;

public class JedisDemo {
    public void execute () {
        Jedis jedis = new Jedis();
        //Jedis jedis1 = new Jedis("44.55.66.7", 3333);

        Boolean hello = jedis.exists("hello");
        System.out.println(hello);

        String s = jedis.get("hello");
        System.out.println(s);

        jedis.set("hello:1", "world:23");

        Long hello1 = jedis.exists("hello", "hello:123");
        System.out.println(hello1);
    }
}

第四部在此笔者在redis里面已经有了一个Hello(key)

package the_mass.redis;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        RedisService redisService = context.getBean(RedisService.class);
        //redisService.testRedis();
        redisService.testRedisTemplate();
    }
}

简单测试

原文地址:https://www.cnblogs.com/dzcici/p/10181322.html