资讯专栏INFORMATION COLUMN

redis-10-spring-boot

Panda / 583人阅读

摘要:说明本文主要介绍使用集成的方式来操作。至于的多带带使用就不必多说了。

[TOC]

说明

本文主要介绍使用spring-boot集成jedis的方式来操作redis。

至于jedis的多带带使用就不必多说了。

此处的集成方式有两种:

手动配置集成jedis

使用spring-boot-starter-data-redis集成

1 手动配置集成jedis 1.1 jar依赖

  
  
    org.springframework.boot
    spring-boot-starter-web
  

  
    org.springframework.boot
    spring-boot-devtools
    runtime
  
  
  
    org.springframework.boot
    spring-boot-starter-test
    test
  
  
  
  
    redis.clients
    jedis
  
  
1.2 配置 1.2.1 外部配置文件

application.yaml

jedis:
  host: 127.0.0.1
  port: 6379
  pool:
    max-idle: 300
    min-idle: 10
    max-total: 600
    max-wait: 1000
    block-when-exhausted: true
1.2.2 java配置类(代替传统的xml配置)

RedisConfig.java

package cn.hylexus.app.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Bean("jedis.config")
    public JedisPoolConfig jedisPoolConfig(//
            @Value("${jedis.pool.min-idle}") int minIdle, //
            @Value("${jedis.pool.max-idle}") int maxIdle, //
            @Value("${jedis.pool.max-wait}") int maxWaitMillis, //
            @Value("${jedis.pool.block-when-exhausted}") boolean blockWhenExhausted, //
            @Value("${jedis.pool.max-total}") int maxTotal) {

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxTotal(maxTotal);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        config.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        config.setJmxEnabled(true);
        return config;
    }

    @Bean
    public JedisPool jedisPool(//
            @Qualifier("jedis.config") JedisPoolConfig config, //
            @Value("${jedis.host}") String host, //
            @Value("${jedis.port}") int port) {
        return new JedisPool(config, host, port);
    }
}
1.3 使用示例
package cn.hylexus.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisServiceImpl implements RedisService {

    // 此处直接注入即可
    @Autowired
    private JedisPool jedisPool;

    @Override
    public String get(String key) {
        Jedis jedis = this.jedisPool.getResource();
        String ret;
        try {
            ret = jedis.get(key);
        } finally {
            if (jedis != null)
                jedis.close();
        }
        return ret;
    }

    @Override
    public boolean set(String key, String val) {
        Jedis jedis = this.jedisPool.getResource();
        try {
            return "OK".equals(jedis.set(key, val));
        } finally {
            if (jedis != null)
                jedis.close();
        }
    }

}
1.4 简单测试
package cn.hylexus.app.service;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import cn.hylexus.app.SpringBootRedisJedispoolApplicationTests;

public class RedisServiceImplTest extends SpringBootRedisJedispoolApplicationTests {

    @Autowired
    private RedisService redisService;

    @Test
    public void testGet() {
        // test set
        boolean status = this.redisService.set("foo", "bar");
        Assert.assertTrue(status);

        // test get
        String str = this.redisService.get("foo");
        Assert.assertEquals("bar", str);
    }

}
1.5 源码地址

https://github.com/hylexus/bl...

2 使用spring-boot-starter-data-redis 2.1 jar依赖

  
  
  
    org.springframework.boot
    spring-boot-starter-data-redis
  
  
    org.springframework.boot
    spring-boot-starter-web
  

  
    org.springframework.boot
    spring-boot-devtools
    runtime
  
  
    org.springframework.boot
    spring-boot-starter-test
    test
  
2.2 配置 2.2.1 外部配置文件

application.yaml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: null
    pool:
      max-idle: 300
      min-idle: 10
      max-active: 600
      max-wait: 1000
    timeout: 0
2.2.2 java配置类
package cn.hylexus.app.config;

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.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 实例化 RedisTemplate 对象
     * 
     */
    @Bean
    public RedisTemplate functionDomainRedisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        this.initRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 序列化设置
     */
    private void initRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }

    @Bean
    public HashOperations hashOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations valueOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations listOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations setOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations zSetOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}
2.3 简单测试
package cn.hylexus.app;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {

    @Autowired
    private ValueOperations valueOperations;

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testStringOps() {
        this.valueOperations.set("k1", "spring-redis");

        Boolean hasKey = this.redisTemplate.hasKey("k1");
        assertEquals(true, hasKey);

        Object str = this.valueOperations.get("k1");
        assertNotNull(str);
        assertEquals("spring-redis", str.toString());
    }
}
2.4 源码地址

https://github.com/hylexus/bl...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/36327.html

相关文章

发表评论

0条评论

最新活动
阅读需要支付1元查看
<