JAVA 调用Redis接口

  • pom.xml
         <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
  • RedisTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

/**
 * Created by yinliang on 2016/4/1.
 */
public class RedisTest {

    private String HOST = "192.168.24.135";
    private Jedis jedis;

    @Before
    public void start() {
        System.out.println("测试开始。。。");
        jedis = new Jedis(HOST);
    }

    @After
    public void end() {
        System.out.println("测试结束。。。");
    }


    @Test
    public void test() {
        System.out.println("nimabi");
    }


    //连接Redis
    @Test
    public void test1() {
        //Connecting to Redis server on localhost

        System.out.println("Connection to server sucessfully");
        //check whether server is running or not
        System.out.println("Server is running: " + jedis.ping());
    }


    /**
     * Redis和Java字符串实例
     */
    @Test
    public void test2() {
        //set the data in redis string
        jedis.set("tutorial-name", "Redis tutorial");
        // Get the stored data and print it
        System.out.println("Stored string in redis:: " + jedis.get("tutorial-name"));
    }

    /**
     * Redis和Java列表示例
     */
    @Test
    public void test3() {
        System.out.println("Connection to server sucessfully");
        //store data in redis list
        jedis.lpush("tutorial-list", "Redis");
        jedis.lpush("tutorial-list", "Mongodb");
        jedis.lpush("tutorial-list", "Mysql");
        // Get the stored data and print it
        List<String> list = jedis.lrange("tutorial-list", 0, 5);
        for (int i = 0; i < list.size(); i++) {
            System.out.println("Stored string in redis:: " + list.get(i));
        }
    }


    /**
     * Redis和Java的键实例
     */
    @Test
    public void test4() {
        System.out.println("Connection to server sucessfully");
        //store data in redis list
        // Get the stored data and print it
        Set<String> strings = jedis.keys("*");
        for (String string : strings) {
            System.out.println(string);
            jedis.del(string);
        }
    }
}
### Java 调用 Redis 示例代码及教程 #### 使用 Jedis 进行基本操作 Jedis 是一个广泛使用的 Redis Java 客户端,能够提供对 Redis 命令的全面支持。下面是一个简单的例子来展示如何通过 Jedis 设置和获取键值: ```java import redis.clients.jedis.Jedis; public class JedisExample { public static void main(String[] args) { // 创建连接到本地运行的 Redis 实例 try (Jedis jedis = new Jedis("localhost")) { System.out.println("Connection to server sucessfully"); // Set the data in redis string variable jedis.set("w3ckey", "Redis tutorial"); // Get the stored data and print it String value = jedis.get("w3ckey"); System.out.println(value); } } } ``` 这段代码展示了怎样创建与 Redis 的连接并执行 `SET` 和 `GET` 操作[^1]。 #### 利用 Lettuce 执行异步命令 Lettuce 支持同步、异步以及响应式编程风格的操作模式。这里给出一段使用其异步功能的例子: ```java import io.lettuce.core.RedisClient; import io.lettuce.core.api.async.RedisAsyncCommands; import java.util.concurrent.ExecutionException; public class AsyncCommandExample { private final RedisClient client = RedisClient.create("redis://localhost:6379/0"); public void asyncSetGet() throws ExecutionException, InterruptedException { var connection = client.connect(); try{ RedisAsyncCommands<String, String> syncCommands = connection.async(); // 发送 SET 请求但不等待回复 syncCommands.set("key","value").get(); // 获取之前设置的 key 对应的值 String result = syncCommands.get("key").get(); System.out.println(result); } finally { connection.close(); client.shutdown(); } } } ``` 此片段说明了如何建立非阻塞通信通道,并发送指令给服务器而不必立即处理返回的结果[^3]。 #### 结合 Spring Data Redis 构建应用程序 对于构建基于 Spring Framework 的项目来说,Spring Data Redis 提供了一套易于集成的方式去管理 Redis 数据源。下面是一份配置类样例加上相应的 Repository 接口定义: ```java @Configuration @EnableRedisRepositories(basePackages = {"com.example.repository"}) public class AppConfig extends AbstractRedisConfiguration { @Bean JedisConnectionFactory jedisConnectionFactory(){ return new JedisConnectionFactory(); } } // 定义一个接口继承自 CrudRepository 或 PagingAndSortingRepository, // 即可获得 CRUD 方法和其他分页查询等功能的支持。 @Repository public interface UserRepository extends CrudRepository<User, Long>{ } ``` 上述配置允许开发者专注于业务逻辑开发而不是底层细节,因为大部分工作已经被框架自动完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值