redis实战(java项目应用)

时间:2022-09-08 17:48:16


首先,简单介绍下Redis,redis是一个key-value存储系统,并提供多种语言的API。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。更详细的介绍可以参照官网(点击打开链接),本文主要介绍redis在工程项目中的具体应用(Redis的Java客户端jedis的使用,贴出jedis源码地址:点击打开链接)  下面是具体的步骤:  


1.下载jar包,本文使用的是jedis-2.5.2.jar,下载地址:http://grepcode.com/snapshot/repo1.maven.org/maven2/redis.clients/jedis/2.5.2现在很多项目使用maven作为项目依赖管理工具,maven只需在pom.xml文件中添加以下依赖即可: redis.clients jedis 2.5.2   


2.下面即是配置类了,看代码:[java] view plain copy

package com.netease.lwt;  
  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.data.redis.connection.RedisConnectionFactory;  
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
import org.springframework.data.redis.core.StringRedisTemplate;  
  
import redis.clients.jedis.JedisPoolConfig;  
  
@Configuration  
@ComponentScan(basePackages="com.netease.lwt.dao")  
public class RedisConfiguration {  
      
    public static final String HOST = "e36d254038ee4529.m.cnhza.kvstore.aliyuncs.com";  
    public static final Integer PORT = 6379;  
    public static final String PASSWORD = "Laowantong2015";  
  
  
    @Bean  
    public RedisConnectionFactory jedisConnectionFactory(){  
       JedisPoolConfig poolConfig = new JedisPoolConfig();    
       poolConfig.setMaxIdle(8);  
       poolConfig.setMinIdle(0);  
       poolConfig.setTestOnBorrow(true);  
       poolConfig.setTestOnReturn(true);  
       poolConfig.setTestWhileIdle(true);  
       JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);  
       jedisConnectionFactory.setHostName(HOST);  
       jedisConnectionFactory.setPort(PORT);         
       jedisConnectionFactory.setPassword(PASSWORD);  
       return jedisConnectionFactory;  
    }  
      
    @Bean  
    public StringRedisTemplate redisTemplate(){  
       StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory());  
       return redisTemplate;  
    }  
}  
  


HOST,PORT,PASSWORD分别是服务器地址,端口,连接密码,其他的详细配置可自己根据项目需求动态设置
  3.接下来就是数据结构的定义了,redis支持包括string,list,set,sorted set,hash等结构。本项目中只用到了Set,SortSet,HashSet,若需要使用redis其他数据结构,可另行定义类。
redis各数据结构所提供的方法,可参考: http://redisdoc.com/index.html。
   (1).redis数据集合名定义(set,get操作需要)
[java] view plain copy
public class RedisSetName {  
    // setName  
      public static final String USERGROUPS = "UserGroups";  
    public static final String GROUPAUCTIONS = "GroupAuctions";  
    public static final String AUCTIONJSONS = "AuctionJsons";  
    public static final String AUCTIONGOODS = "AuctionGoods";  
    public static final String AUCGOODIMAGES = "AucGoodImages";  
    public static final String GROUPINFOS = "GroupInfos";  
    public static final String USERAUCTIONISREMIND = "UserAuctionIsRemind";     
    public static final String USERFRIENDREMARK = "UserFriendRemark";     
    public static final String GROUPUSERS = "GroupUsers";    
    public static final String USERINFOS = "UserInfos";  
    public static final String RELUSERGROUPINFOS = "RelUserGroupInfos";  
    public static final String GROUPUSEREMARK = "GroupUserRemark";  
  
}  

    (2)下面就是dao层一些操作定义了。见具体代码:因代码贴出篇幅过大,下面就只给出sortedset的dao层定义,其他的数据结构操作类似。
     本文定义了redis中sortedset类型数据的增删改查操作,可根据需要添加方法。

[java] view plain copy
package com.netease.lwt.dao;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Set;  
import javax.inject.Inject;  
import org.springframework.data.redis.core.StringRedisTemplate;  
import org.springframework.stereotype.Repository;  
@Repository  
public class RedisSetRepository {  
     private StringRedisTemplate redisTemplate;  
    @Inject  
    public RedisSetRepository(StringRedisTemplate redisTemplate){  
       this.redisTemplate = redisTemplate;  
    }  
    public Long add(String setName, String value) {  
       Long num = redisTemplate.opsForSet().add(setName, value);  
       return num;  
    }  
    public Long add(String setName, List values) {  
     Long num = new Long(0);  
     for(String value : values){   
       num += redisTemplate.opsForSet().add(setName, value);  
      }  
    return num;  
    }   
    public Long remove(String setName, String value){  
     Long num = redisTemplate.opsForSet().remove(setName, value);  
     return num;  
    }   
    public void removeAll(String setName) {  
     redisTemplate.opsForSet().remove(setName, redisTemplate.opsForSet().members(setName));  
    }   
    public List getAll(String setName){  
     setMembers = redisTemplate.opsForSet().members(setName);  
     return new ArrayList(setMembers);  
    }  
      
}  
   (3)接下来就可以在自己的Service层定义自己的方法了,比如你把用户信息缓存了,那在Service中需要获取用户信息的时候就可以通过上数dao层定义的方法上获取了。下面贴出本项目中一个使用实例
[html] view plain copy
/************************************** Redis相关增加/修改/删除操作 **************************************************************/  
@Override  
public void save(Group group) {  
    groupRepository.save(group);  
    redisHashSetRepository.set(  
            RedisSetName.generateSetName(RedisSetName.GROUPINFOS,  
                    group.getIm()), "name", group.getName());  
}  
  
public void deleteGroup(Group group) {  
    groupRepository.deleteByIm(group.getIm());  
    redisHashSetRepository.remove(  
            RedisSetName.generateSetName(RedisSetName.GROUPINFOS,  
                    group.getIm()), "name");  
}  
[html] view plain copy
  
/*************************************** Redis相关查询操作**************************************************************/
@Override
public List findGroupImsByUser(String uid) throws CustomException {
return ims = redisSetRepository.getAll(RedisSetName.generateSetName(RedisSetName.USERGROUPS, uid));
}