SpringBoot整合Redis

导入redis依赖


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

配置类

package com.itcast.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import lombok.Getter;
import lombok.Setter;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by n00216283 on 2018/6/25.
 */
@Getter
@Setter
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfiguration
{
    @Value("${spring.redis.host}")
    private String redisIp;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;


    @Bean
    public JedisPoolConfig jedisPoolConfig()
    {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    public JedisPool jedisPool(JedisPoolConfig config) //config 对象是上面的注入的
    {
        JedisPool jedisPool = new JedisPool(config, redisIp, port, timeout);

        return jedisPool;
    }
}

 操作redis的jedis类

package com.itcast.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by n00216283 on 2018/6/26.
 */
@Component
@Slf4j
public class RedisRepository
{
    @Autowired
    private JedisPool jedisPool;

    /**
     * 从redis中查询iam token
     * @param key
     * @return
     */
    public String getString(String key)
    {
        String value = null;
        try (Jedis jedis = jedisPool.getResource())
        {
            if (jedis != null)
            {
                value = jedis.get(key);
            }
        }
        catch (Exception e)
        {
            log.error("get value from redis failed. key: " + key, e);
        }

        return value;
    }

    /**
     * 将iam token存入redis
     * @param key
     * @param value
     */
    public void setString(String key, String value)
    {
        try (Jedis jedis = jedisPool.getResource())
        {
            if (jedis != null)
            {
                jedis.set(key, value);
            }
        }
        catch (Exception e)
        {
            log.error("set value to rdis failed. key: " + key, e);
        }
    }

    /**
     * 设置key的过期时间,超时时间是相对时间,单位s
     * @param key
     * @param expireTime
     */
    public void expire(String key, int expireTime)
    {
        try (Jedis jedis = jedisPool.getResource())
        {
            if (jedis != null)
            {
                jedis.expire(key, expireTime);
            }
        }
        catch (Exception e)
        {
            log.error("set expire time failed for key " + key, e);
        }
    }
}

 redisRepository.setString("test", "test_value"); 操作redis

package com.itcast;

import com.itcast.config.RedisRepository;

import org.omg.PortableInterceptor.ServerRequestInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.Charset;

@Controller
@SpringBootApplication
@Configuration
@ComponentScan(basePackages = "com.itcast")
public class HelloApplication
{

    @Autowired
    private RedisRepository redisRepository;

    @RequestMapping("hello")
    @ResponseBody
    public String hello()
    {

        redisRepository.setString("test", "test_value");
        return "hello world!";
    }


    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter(){
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }


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

        SpringApplication springApplication = new SpringApplication(HelloApplication.class);
        //关闭启动logo
//        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run(args);

    }

}

application.yml配置

server:
  port: 8000
logging:
  level: debug


spring:
  redis:
    database:0
    host:192.168.13.135
    port: 6379
    timeout: 20000
    pool:
      min-idle: 10
      max-idle: 500
      max-active: 500

 

可以看到建立了连接

 

其实数据库也是有数据的

root@ubuntu-130:~# redis-cli -h 127.0.0.1 -p 6379 -a redis
127.0.0.1:6379>
127.0.0.1:6379>
127.0.0.1:6379> keys *
1) "test"
127.0.0.1:6379> get test
"test_value"
127.0.0.1:6379>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值