springboot2使用jedis连接redis

        在springboot1.5.x版本中,springboot默认是使用jedis来操作redis的,但是在springboot2.x版本,默认是使用lettuce来操作数据库,所以配置有些差别。具体的使用参照下面的步骤:

1,创建一个springboot2项目

      pom配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jack</groupId>
    <artifactId>springboot2-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot2-redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>-->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--1.5的版本默认采用的连接池技术是jedis,2.0以上版本默认连接池是lettuce, 因为此次是采用jedis,所以需要排除lettuce的jar -->
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <groupId>redis.clients</groupId>
                    <artifactId>jedis</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.10.2</version>
            <!--<version>3.0.1</version>-->
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 spring2.X集成redis所需common-pool2,使用jedis必须依赖它 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

2,配置jedis

获取redis配置的节点信息

package com.jack.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.List;

/**
 * Created By Jack on 2019/7/10
 *
 * @author Jack
 * @date 2019/7/10 19:48
 * @Description:
 */
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterProperties {
    /**
     * cluster nodes,redis节点数组
     */
    private List<String> nodes=new ArrayList<>();

    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }

}

jedis的配置类信息:

package com.jack.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created By Jack on 2019/7/10
 *
 * @author Jack
 * @date 2019/7/10 19:49
 * @Description:
 */
@Configuration
@ConditionalOnClass(RedisClusterConfig.class)
@EnableConfigurationProperties(RedisClusterProperties.class)
public class RedisClusterConfig {
    /**
     * 获取redis的集群的配置ip+端口
     */
    @Resource
    private RedisClusterProperties redisClusterProperties;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public JedisCluster redisCluster() {

        Set<HostAndPort> nodes = new HashSet<>();
        for (String node : redisClusterProperties.getNodes()) {
            String[] parts = StringUtils.split(node, ":");
            Assert.state(parts.length == 2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'");
            nodes.add(new HostAndPort(parts[0], Integer.valueOf(parts[1])));
        }
        //没有配置连接池使用默认的连接池
        //return new JedisCluster(nodes);

        //创建集群对象
        JedisCluster jedisCluster = null;
        if (!StringUtils.isEmpty(password)) {
            jedisCluster = new JedisCluster(nodes, 6000, 1500, 3, password, jedisPoolConfig());
        } else {
            jedisCluster = new JedisCluster(nodes,6000,jedisPoolConfig());
        }
        return jedisCluster;
    }

    /**
     * jedis的连接池
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxIdle(20);
        jedisPoolConfig.setMaxWaitMillis(24000);
        return jedisPoolConfig;
    }



}

 

 

redis的模板配置:

package com.jack.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created By Jack on 2019/7/10
 *
 * @author Jack
 * @date 2019/7/10 19:30
 * @Description:
 */
@Configuration
public class JedisRedisConfig {
    /**
     * redis模板配置
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        //设置序列化,使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper =new ObjectMapper();
        //指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

 

3,配置文件信息

server:
  port: 9090
spring:
  redis:
    password: ""
    cluster:
      nodes:
      - x.x.x.x:6379
    jedis:
      pool:
        min-idle: 1
        max-idle: 8
        max-wait: 1000ms
        max-active: 8
    timeout: 2000ms

 

4,封装jedis操作服务

package com.jack.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

/**
 * Created By Jack on 2018/9/20
 *
 * @author Jack
 * @date 2018/9/20 15:03
 * @Description:
 */
@Service
public class JedisRedisService {
    @Autowired
    private JedisCluster jedisCluster;

    public void set(String key,String value){
        jedisCluster.set(key, value);
    }

    public String get(String key) {
        return jedisCluster.get(key);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key, Class<? extends Serializable> c) {
        String s = get(key);
        return (T) JSONObject.parseObject(s,c);
    }


    public long set(String key,String value,int expireTime){
        jedisCluster.set(key, value);
        return jedisCluster.expire(key, expireTime);
    }

    public long set(String key, Object obj, int expireTime) {
        String jsonString = JSONObject.toJSONString(obj);
        return set(key, jsonString, expireTime);
    }

    public long del(String key) {
        return jedisCluster.del(key);
    }

    /**
     * 在名称为key的list尾添加元素
     * @param key
     * @param list
     */
   public void add(String key,List<String> list){
        if(list != null && list.size() > 0){
            String[] vals = list.toArray(new String[list.size()]);
            jedisCluster.rpush(key, vals);
        }
    }

    /**
     *
     * @param key
     * @param value
     */
    public void add(String key, String value) {
        jedisCluster.rpush(key, value);
    }

    /**
     * 返回名称为key的list的长度
     * @param key
     * @return
     */
   public Long getSize(String key){
        return jedisCluster.llen(key);
    }

    /**
     * 返回并删除名称为key的list中的首元素
     * @param key
     * @return
     */
    public String getFirst(String key){
        return jedisCluster.lpop(key);
    }


    /**
     * 从左获取数据
     * @param key
     * @param count 获取条数
     * @return
     */
    public List<String> getLrange(String key,  long  count){
        return getLrange(key, 0, count-1);
    }

    /**
     * 从左获取数据(注意:开始下班0,结束下标1;总共获取2条数据)
     * @param key
     * @param start 开始下标(包含)
     * @param end 结束下标(包含)
     * @return
     */
    public List<String> getLrange(String key, long start, long  end){
        return jedisCluster.lrange(key, start, end);
    }



    /**
     * 删除集合中元素
     *
     * @param key
     * @param count 删除数量
     */
   public void leftDel(String key, int count) {
        for (int i = 0; i < count; i++) {
            jedisCluster.lpop(key);
        }
    }



    /**
     * 获取keys
     * @param pattern
     * @return
     */
    public TreeSet<String> keys(String pattern){
        TreeSet<String> keys = new TreeSet<>();
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        for(String k : clusterNodes.keySet()){
            JedisPool jp = clusterNodes.get(k);
            try (Jedis connection = jp.getResource()) {
                keys.addAll(connection.keys(pattern));
            } catch (Exception ignored) {
            }
        }
        return keys;
    }


    public String rename(String oldKey, String newKey) {
        return jedisCluster.rename(oldKey, newKey);
    }

    public List<String> ll(String key) {
        return jedisCluster.lrange(key, 0, -1);
    }

    public Long lpush(String key, String... va) {
        return jedisCluster.lpush(key, va);
    }

    public void lpush(String key, List<String> list) {
        if(list != null && list.size() > 0){
            String[] vals = list.toArray(new String[list.size()]);
            jedisCluster.lpush(key, vals);
        }
    }
}

 

 

5,测试

1)创建一个实体类

package com.jack.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * Created By Jack on 2019/7/10
 *
 * @author Jack
 * @date 2019/7/10 20:17
 * @Description:
 */
@Data
public class Person implements Serializable {

    private static final long serialVersionUID = -2882592645848747970L;
    private int age;
    private String sex;
    private String name;
}

2)测试controller

package com.jack.controller;

import com.jack.entity.Person;
import com.jack.service.JedisRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created By Jack on 2019/7/10
 *
 * @author Jack
 * @date 2019/7/10 16:32
 * @Description:
 */
@RestController
@RequestMapping("redis")
public class RedisTestController {
    @Autowired
    private JedisRedisService jedisRedisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 使用jedis插入key,value
     * @return
     */
    @RequestMapping("test1")
    public String redisTest1() {
        jedisRedisService.set("jack","rose");
        System.out.println("插入字符串成功");
        System.out.println("获取字符串:"+jedisRedisService.get("jack"));
        return "success";
    }

    /**
     * 使用StringRedisTemplate插入key,value
     * @return
     */
    @RequestMapping("test2")
    public String redisTest2() {
        stringRedisTemplate.opsForValue().set("jack2","rose2");
        System.out.println("插入字符串成功");
        System.out.println("获取字符串:"+stringRedisTemplate.opsForValue().get("jack2"));
        return "success";
    }

    /**
     * 使用jedis插入对象
     * @return
     */
    @RequestMapping("test3")
    public String redisTest3() {
        Person p = new Person();
        p.setAge(18);
        p.setName("jack");
        p.setSex("男");
        jedisRedisService.set("p",p,300);
        System.out.println("插入字符串成功");
        System.out.println("获取对象的值:"+jedisRedisService.get("p"));
        return "success";
    }

}

 

主类代码:

package com.jack;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot2RedisApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Springboot2RedisApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("*************启动成功**********************");
    }
}

 

启动程序:

使用postman访问:

http://localhost:9090/redis/test1

http://localhost:9090/redis/test2

http://localhost:9090/redis/test3

 

输出如下:

*************启动成功**********************
2019-07-10 20:46:58.593  INFO 12808 --- [nio-9090-exec-5] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-10 20:46:58.593  INFO 12808 --- [nio-9090-exec-5] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-07-10 20:46:58.598  INFO 12808 --- [nio-9090-exec-5] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
插入字符串成功
获取字符串:rose
插入字符串成功
获取字符串:rose2
插入字符串成功
获取对象的值:{"age":18,"name":"jack","sex":"男"}

 

 

 

 

 

 

当多个线程频繁地使用Redis时,使用连接池可以提高应用程序的性能。下面是使用连接池集成Redis的步骤: 1. 在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.10.0</version> </dependency> ``` 2. 创建Redis连接池配置类。以下是一个示例: ```java @Configuration public class RedisPoolConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.maxIdle}") private int maxIdle; @Value("${spring.redis.maxTotal}") private int maxTotal; @Value("${spring.redis.maxWaitMillis}") private long maxWaitMillis; @Bean public JedisPool jedisPool() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(maxIdle); poolConfig.setMaxTotal(maxTotal); poolConfig.setMaxWaitMillis(maxWaitMillis); JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, password); return jedisPool; } } ``` 在上面的代码中,我们使用JedisPoolConfig来配置我们的连接池,并创建一个JedisPool bean。您可以根据实际情况调整连接池的最大空闲连接数,最大连接数和最长等待时间。 3. 在您的服务类或控制器类中使用Redis连接池。您可以使用@Autowired注解注入JedisPool bean,然后使用它来获取Jedis实例并执行Redis操作。以下是一个示例: ```java @Autowired private JedisPool jedisPool; public void setValue(String key, String value) { try (Jedis jedis = jedisPool.getResource()) { jedis.set(key, value); } } public String getValue(String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.get(key); } } ``` 在上面的代码中,我们使用了try-with-resources语句来确保在使用Jedis实例后关闭连接。这可以确保连接池中的连接得到正确释放。 这就是使用连接池集成Redis的步骤。希望这可以帮助您提高您的应用程序性能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值