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":"男"}

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章