在 Java 中添加 Redis<spring>

  Redis 的 Java 客户端很多,官方推荐的有三种:

  • jedis
  • lettuce
  • redisson

  Spring对Redis客户端进行了整合,提供了 Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis

 

  • spring中操作redis
  • springboot 中操作redis

 

windows版本redis下载安装教程 

 

  • spring 中操作 redis

 

pom.xml中添加 redis依赖:

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.8.0</version>
      <type>jar</type>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.5.0.RELEASE</version>
    </dependency>

配置redis

    <bean id="connectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="127.0.0.1" p:port="6379" p:password="123456"/>
    <bean class="org.springframework.data.redis.core.RedisTemplate" id="redisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>

 

参考文章连接

 

使用 jedis 操作 Redis 的步骤:

  1. 获取连接
  2. 执行操作
  3. 关闭连接
public class jedisTest {

    @Test
    public void testRedis(){
        //获取连接
        Jedis jedis = new Jedis("localhost", 6379);
        //执行具体操作
        jedis.set("name","xiaominghaha");
        String value = jedis.get("name");
        System.out.println(value);

        jedis.hset("myhash","addr","word");
        String hValue = jedis.hget("myhash","addr");
        System.out.println(hValue);

        Set<String> keys = jedis.keys("*");
        for(String key : keys){
            System.out.println(key);
        }

        //关闭连接
        jedis.close();
    }
}

 

posted @ 2023-01-30 11:12  没有好想法  阅读(58)  评论(0)    收藏  举报