Java项目集成redis

这篇博客介绍了Java项目集成Redis的两种常见方式:1) 使用Jedis直连,详细阐述了导入依赖、创建客户端、执行命令及关闭客户端的步骤,并提到一般会编写JedisUtils工具类;2) 利用RedisTemplate模板技术,讲解了从配置到创建RedisTemplate对象并进行操作的完整过程。文中还提及需要引入fastjson依赖。

集成redis进入项目通常有两种方式

1、JEDIS直连。

Step1、导入Jedis依赖:

  <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

Step2、创建redis的客户端

 //创建了一个Redis的客户端链接
        Jedis client = new Jedis("127.0.0.1",6379);

Step3、执行相应的redis命令

client.set("boot","jedis");
        client.hset("WKEY","PKEY","HASH");

Step4、关闭客户端

 client.close();

运行后查看结果(打开redis客户端查看)

在这里插入图片描述

为了方便代码编写,我们一般会写一些JedisUtils工具类,以下为简单的JedisUtils工具类的编写示例,CSDN还有很多好心的老哥写了很多更好的~

package ver.s86springbootredis.jedis;

import redis.clients.jedis.Jedis;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class JedisUtils
{
    private static String host ="127.0.0.1";
    private static int port =6379;
    private static Jedis jedis=null;
    private int poolsize = 10;
    //pool
    private static List<Jedis> pool = new LinkedList<>();

    private void initPools()
    {
        if (pool.size()<=0)
        {
            for (int i = 0; i < poolsize ; i++)
            {
                pool.add(new Jedis(host,port));
            }
        }

    }
    public JedisUtils()
    {
        jedis =  new Jedis(host,port);
    }
    public JedisUtils(int poolsize)
    {
        this.poolsize = poolsize;
        initPools();
    }

    public static Jedis getConnection(String host,int port)
    {
        jedis =  new Jedis(host,port);
        return jedis;
    }
    public static Jedis getConnection()
    {
        jedis =  pool.get(new Random().nextInt(pool.size()));
        return jedis;
    }

    public static void close()
    {
        if(jedis !=null)
        {
            jedis.close();
        }
    }
    public static void setString(String key ,String value)
    {
        if(jedis == null )
        {
            getConnection();
        }
        jedis.set(key,value);
    }

}

2、RedisTemplate模板技术连接。

Spring封装的一个redis连接框架

Step1、创建一个Configuration类

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
//表明这是一个Configuration类
@Configuration
public class RedisConfig {}

Step2、加入redis连接的配置 :

spring.redis.host=127.0.0.1
spring.redis.port=6379
#redis密码默认为空值。
spring.redis.password=
spring.redis.timeout=300
spring.redis.jedis.pool.max-active=8
#池子最多有多少个僵尸链接
spring.redis.jedis.pool.max-idle=8
#是否开启SSL加密链接
spring.redis.ssl=false

Step3、写一个返回RedisTemplate对象的方法,并且将RedisConnectionFactory作为参数默认注入:

@Bean  
public RedisTemplate getTemplate(RedisConnectionFactory factory)

Step4、创建一个RedisTemplate对象并且绑定序列化器(key的序列化器和value的序列化器):

  RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //创建字符串的序列化器,用于给key值做序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);

        //创建一个Value的序列化器,用于给Value做序列
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);

Step5、设置RedisTemplate的连接工厂:

redisTemplate.setConnectionFactory(factory);

Step6、返回redisTemplate对象

return redisTemplate;

Step7、创建一个Controller类,注入redisTemplate对象,再进行相应的操作

package ver.springbootredistemplate.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SaveController {
    //@Resouse
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("/save")
    public String saveKey(@RequestParam("key") String key,
                          @RequestParam("value") String value)
    {
        //opsForValue 操作字符串类型的数据的工具方法
       ValueOperations stringType =  redisTemplate.opsForValue();
       stringType.set(key,value);
        HashOperations hashType  = redisTemplate.opsForHash();
        hashType.keys(hashType);

        ListOperations listType = redisTemplate.opsForList();


        SetOperations setType = redisTemplate.opsForSet();
        ZSetOperations zsetType = redisTemplate.opsForZSet();
        return "success";
    }
}

上面的代码中需要导入alibaba的fastjson依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值