redis的使用

参考地址:

http://blog.csdn.net/mynoteblog/article/details/54927491

项目分享地址:

 https://pan.baidu.com/s/1bo2XOuF

1.redis安装

在前面已经讲过了

地址:

http://www.cnblogs.com/yun965861480/p/6273451.html 

2.redis主要api

 jedis只提供存储String与byte数据类型,所以在我们的API中需要将需要存储的数据转换一下

这是主要提供的几个API,主要是将需要存储的对象转换为JSON字符串来进行存储。

接口 : RedisService 

package com.qi.util.service;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
//import java.util.function.Supplier;

/**
 * redis缓存接口。
 *
 * 缓存时间单位默认分钟,
 * 默认timeout值为5,
 * 没有timeout和timeunit的方法默认不设置有效时间,永久有效。
 */
public interface RedisService {

    int EXPIRE_TIME_1 = 1;

    int EXPIRE_TIME_2 = 2;

    int EXPIRE_TIME_5 = 5;

    int EXPIRE_TIME_7 = 7;

    int EXPIRE_TIME_15 = 15;
    
    int EXPIRE_TIME_30 = 30;


    <T> void put(String key, T obj);
    
    <T> void put(String key, T obj, int timeout);
    
    <T> void put(String key, T obj, int timeout, TimeUnit unit);

    <T> T get(String key, Class<T> cls);

    <E, T extends Collection<E>> T get(String key, Class<E> cls, Class<T> collectionClass);

//    <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier);
//    <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout);
//    <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit);
//    <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh);
//
//    <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier);
//    <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout);
//    <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit);
//    <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh);

    boolean exists(String key);

    void delete(String key);

    boolean expire(String key, long timeout, TimeUnit timeUnit);
    boolean expire(String key, long timeout);
    
    void put(String key, String value);
    void put(String key, String value, int timeout);
    void put(String key, String value, int timeout, TimeUnit unit);

    String get(String key);
}

接口实现:

package com.qi.util.service.impl;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
//import java.util.function.Supplier;

import javax.annotation.Resource;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.qi.util.JsonUtils;
import com.qi.util.service.RedisService;

@Component("redisService")
public class RedisServiceImpl implements RedisService {

    @Resource
    private StringRedisTemplate redisTemplate;

    public <T> void put(String key, T obj) {
        redisTemplate.opsForValue().set(key, JsonUtils.toJson(obj));
    }

    public <T> void put(String key, T obj, int timeout) {
        put(key, obj, timeout, TimeUnit.MINUTES);
    }

    public <T> void put(String key, T obj, int timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JsonUtils.toJson(obj), timeout, unit);
    }
    
    public <T> T get(String key, Class<T> cls) {
        return JsonUtils.fromJson(redisTemplate.opsForValue().get(key), cls);
    }
    
    public <E, T extends Collection<E>> T get(String key, Class<E> cls, Class<T> collectionClass) {
        return JsonUtils.fromJson(redisTemplate.opsForValue().get(key), cls, collectionClass);
    }

    /*public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier) {
        T t = get(key, cls);
        if (t == null) {
            t = supplier.get();
            if (t != null) {
                put(key, t);
            }
        }
        return t;
    }

    public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout) {
        T t = get(key, cls);
        if (t == null) {
            t = supplier.get();
            if (t != null) {
                put(key, t, timeout);
            }
        }
        return t;
    }

    public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit) {
        T t = get(key, cls);
        if (t == null) {
            t = supplier.get();
            if (t != null) {
                put(key, t, timeout, unit);
            }
        }
        return t;
    }

    public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh) {
        T t = get(key, cls);
        if (t == null) {
            t = supplier.get();
            if (t != null) {
                put(key, t, timeout, unit);
            }
        } else {
            if (refresh) {
                expire(key, timeout, unit);
            }
        }
        return t;
    }

    public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier) {
        T t = get(key, cls, collectionCls);
        if (t == null || t.isEmpty()) {
            t = supplier.get();
            if (t != null && t.size() > 0) {
                put(key, t);
            }
        }
        return t;
    }

    public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout) {
        return putIfAbsent(key, cls, collectionCls, supplier, timeout, TimeUnit.SECONDS);
    }

    public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit) {
        return putIfAbsent(key, cls, collectionCls, supplier, timeout, unit, false);
    }

    public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh) {
        T t = get(key, cls, collectionCls);
        if (t == null || t.isEmpty()) {
            t = supplier.get();
            if (t != null && t.size() > 0) {
                put(key, t, timeout, unit);
            }
        } else {
            if (refresh) {
                expire(key, timeout, unit);
            }
        }
        return t;
    }*/


    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public boolean expire(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }
    
    public boolean expire(String key, long timeout) {
        return expire(key, timeout, TimeUnit.MINUTES);
    }
    
    public void put(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void put(String key, String value, int timeout) {
        put(key, value, timeout, TimeUnit.MINUTES);
    }

    public void put(String key, String value, int timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    
}

3.redis

相关配置

a.添加依赖,主要是 redis,jedis的依赖

<!-- redis start -->  
        <dependency>  
            <groupId>redis.clients</groupId>  
            <artifactId>jedis</artifactId>  
            <version>${jedis.version}</version>  
         </dependency>  
         <dependency>  
            <groupId>org.springframework.data</groupId>  
            <artifactId>spring-data-redis</artifactId>  
            <version>${spring.data.redis.version}</version>  
         </dependency>  
         <!-- redis end -->  
         <!-- jackson -->  
        <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-core</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-databind</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-annotations</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
  
        <!-- fastjson -->  
        <!-- StringUtils -->  
        <dependency>  
            <groupId>org.apache.commons</groupId>  
            <artifactId>commons-lang3</artifactId>  
            <version>3.4</version>  
        </dependency>  

b.添加redis工厂配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:p="http://www.springframework.org/schema/p"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">  
  
    <!-- blockWhenExhausted: 从Pool中获取Jedis对象,Pool资源耗尽后阻塞maxWaitMillis参数指定时间 -->  
    <!-- maxWaitMillis: 从Pool中获取Jedis对象超时时间 -->  
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"  
          p:minIdle="2"  
          p:maxIdle="5"  
          p:maxTotal="8"  
          p:maxWaitMillis="2000"  
          p:testOnBorrow="false"  
          p:testOnReturn="false"  
          p:testWhileIdle="true"  
          p:blockWhenExhausted="true" />  
  
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="usePool" value="true" />  
        <property name="hostName" value="192.168.158.129" />  
        <property name="port" value="6379" />  
        <property name="password" value="" />  
        <property name="timeout" value="2000" />  
        <constructor-arg name="poolConfig" ref="jedisPoolConfig" />  
    </bean>  
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
         <property name="connectionFactory" ref="jedisConnectionFactory" />  
    </bean>  
</beans> 

4.测试

测试contoller

package com.qi.quartz.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.maven.web.entity.UserInfo;
import com.qi.util.service.UserService;

@Controller
@RequestMapping("/redis")
public class RedisController {
    
    @Resource
    private UserService userService;
    
    @ResponseBody
    @RequestMapping(value="/userInfo",method=RequestMethod.GET)
    public String getUserInfo(@RequestParam Long uid) {
        try {
            UserInfo userInfo = userService.getUserInfo(uid);
            if (userInfo!=null) {
                return "您要获取的用户名称是:"+userInfo.getUserName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "获取用户信息失败";
    }

}

使用的userService

package com.qi.util.service.impl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.maven.web.entity.UserInfo;
import com.qi.util.JsonUtils;
import com.qi.util.service.RedisService;
import com.qi.util.service.UserService;

@Service
public class UserServiceImpl implements UserService{
    
    private static final String USER_INFO = "USER_";
    
    @Resource
    private RedisService redisService;

    public UserInfo getUserInfo(Long uid) {
        String json = redisService.get(USER_INFO+uid);  
        if(json==null){  
            //测试中,创建了一个用户信息,实际应用中应该从数据库中读取数据。
            UserInfo userInfo = new UserInfo();
            userInfo.setId(1L);
            userInfo.setAge(22);
            userInfo.setUserName("dubbo");
            
            if(userInfo!=null){  
                redisService.put(USER_INFO+uid, userInfo, 1, TimeUnit.HOURS);  
            }  
            return userInfo;  
        }  
        //也可以直接获取
//        UserInfo temp = redisService.get(USER_INFO+uid,UserInfo.class);  
  
        return JsonUtils.fromJson(json, UserInfo.class);  
    }

}

访问地址即可测试,查看数据的来源。

http://localhost:8080/QuartzDemo/redis/userInfo?uid=1

原文地址:https://www.cnblogs.com/yun965861480/p/6388606.html