Redis——java代码读写redis

一,简单Jedis读写

     

Jedis jedis=new Jedis("127.0.0.1",6379);//连接的是我本地的服务
		System.out.println("成功连接到服务器==");

		/*存取string类型*/
		jedis.set("name", "lhc");
		model.addAttribute("name",jedis.get("name"));

		/*存取hash类型*/
		jedis.hset("hash", "k1", "v1");
		jedis.hset("hash", "k2", "v2");
		jedis.hset("hash", "k3", "v3");
		model.addAttribute("hash",jedis.hvals("hash"));

	    /*存取list*/
		jedis.lpush("student", "lhc");
		jedis.lpush("student", "水田如雅");
		jedis.lpush("student", "杰伦哥哥");
		List<String> stuList=jedis.lrange("student", 0, 2);
		model.addAttribute("stuList",stuList.toString());

		/*存取set*/
		jedis.sadd("person","lhc");
		jedis.sadd("person","水田");
		jedis.sadd("person","小白");
		model.addAttribute("people",jedis.smembers("person"));

		/*存取zset*/
		jedis.zadd("animal", 0, "cat");
		jedis.zadd("animal", 0, "dog");
		jedis.zadd("animal", 0, "sheep");
		model.addAttribute("animal",jedis.zrange("animal", 0, 2));

		//查看服务是否允许
		System.out.println("服务器正在连通中。。。状态:"+jedis.ping());

二,使用连接池读写

     JedisPool与ShardedJedisPool:

        JedisPool连一台Redis,ShardedJedisPool连Redis集群,通过一致性哈希算法决定把数据存到哪台上,算是一种客户端负载均衡,所以添加是用这个(Redis 3.0之后支持服务端负载均衡) 。

    使用SharedJedisPool操作Redis集群工具类:

public class RedisDao {

	private static final Logger logger = Logger.getLogger(RedisDao.class);
	@Autowired
	private ShardedJedisPool shardedJedisPool;

	public void set(String key, String value) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.set(key, value);

        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	public String get(String key) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		String result = "";
		try {
			result = jedis.get(key);

        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;

	}

	public Long hset(String key, String field, String value) {
		ShardedJedis jedis = shardedJedisPool.getResource();

		Long result = null;
		try {
			result = jedis.hset(key, field, value);

        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
	}

	public String hget(String key, String field) {
		ShardedJedis jedis = shardedJedisPool.getResource();

		String result = null;
		try {
			result = jedis.hget(key, field);

        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
	}

	public List<String> lrange(String key,long start,long end) {
		ShardedJedis jedis = shardedJedisPool.getResource();

		List<String> result = null;
		try {
			result = jedis.lrange(key, start, end);;

        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
	}

	public Long del(String key) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		Long result = null;
		try {
			result = jedis.del(key);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
	}

	public void rpush(String key, String... value) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.rpush(key,value);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	public void lpush(String key, String... value) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.lpush(key,value);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	public void lpop(String key) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.lpop(key);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	public void rpop(String key) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.rpop(key);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	public void lrem(String key,int count,String value) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		try {
			jedis.lrem(key,count,value);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return;
	}

	/**
     * 添加key value 并且设置存活时间
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(String key,String value,int liveTime){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	try {
    		this.set(key, value);
    		jedis.expire(key, liveTime);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
    }

    /**
     * 检查key是否已经存在
     * @param key
     * @return
     */
    public boolean exists(String key){
    	ShardedJedis jedis = shardedJedisPool.getResource();
		boolean result =false;
		try {
			result=jedis.exists(key);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取一个key的模糊匹配总数
     * @param key
     * @return
     */
    public int getKeyCount(String key) {
		ShardedJedis jedis = shardedJedisPool.getResource();
		Set<String> result = null;
		try {
			result = jedis.getShard(key).keys(key + "*");
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result.size();
	}

    /**
     * 查看redis里有多少数据
     */
    @SuppressWarnings("deprecation")
	public long dbSize(){
    	ShardedJedis jedis = shardedJedisPool.getResource();
		Set<String> result = null;
		try {
			 result=jedis.getShard("").keys("*");
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result.size();
     }

	public long sadd(String key,String... value){
    	ShardedJedis jedis = shardedJedisPool.getResource();
		long result = 0l;
		try {
			result= jedis.sadd(key,value);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public Boolean sismember(String key,String value){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	Boolean result = false;
		try {
			result= jedis.sismember(key,value);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public Set smembers(String key){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	Set result = null;
		try {
			result= jedis.smembers(key);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public long zadd(String key,int sequence,String value){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	long result = 0l;
		try {
			result= jedis.zadd(key,sequence,value);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public Set<String> zrange(String key,long start,long end){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	Set<String> result = null;
		try {
			result= jedis.zrange(key,start,end);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public String hmset(String key,Map map){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	String result = null;
		try {
			result= jedis.hmset(key,map);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public Map<String,String> hgetAll(String key){
    	ShardedJedis jedis = shardedJedisPool.getResource();
    	Map<String,String> result = null;
		try {
			result= jedis.hgetAll(key);
         } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	shardedJedisPool.returnBrokenResource(jedis);
        } finally {
        	shardedJedisPool.returnResource(jedis);
        }
        return result;
     }

	public ShardedJedisPool getShardedJedisPool() {
		return shardedJedisPool;
	}

	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}
}

   项目中还需加入redis的property文件和bean配置:

<!-- 读入属性文件 -->
	<bean id="propretyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:conf/redis.properties</value>
			</list>
		</property>
	</bean>

    <!-- redis 配置 -->

    <bean id="redisDao" class="com.upcloud.demo.redis.dao.RedisDao" scope="prototype">
        <property name="shardedJedisPool">
			<ref bean="shardedJedisPool"/>
		</property>
    </bean>

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
	<property name="maxTotal" value="${redis.maxActive}" />    <!--最大连接数-->
	    	<property name="maxIdle" value="${redis.maxIdle}" />     <!--最大空闲数-->
	    	<property name="maxWaitMillis" value="${redis.maxWait}" />    <!--最大等待时间ms-->
	    	<property name="testOnBorrow" value="false" />
	</bean>  

	<bean id="jedis.shardInfo" class="redis.clients.jedis.JedisShardInfo">
	    	<constructor-arg index="0" value="${redis.host}" />
	    	<constructor-arg index="1" value="${redis.port}" />
	</bean>  

	<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
	<constructor-arg index="0" ref="jedisPoolConfig" />
	      <constructor-arg index="1">
	          <list>
	           <ref bean="jedis.shardInfo" />
	          </list>
	      </constructor-arg>
	</bean>
时间: 2024-09-30 09:03:08

Redis——java代码读写redis的相关文章

redis-关于Redis数据库的java代码多线程读写性能问题,希望可以帮忙看看、、、

问题描述 关于Redis数据库的java代码多线程读写性能问题,希望可以帮忙看看... 渣渣一枚..由于项目关系,需要用到内存数据库来存key-value所以就开始研究redis这个数据库.现在已经把redis放在了CentOS的测试服务器上,然后通过网上的资料写了链接代码! 测试用了100个线程,每个线程插入10000条数据,结果竟然花了**200s**, 同事用memcached测试同样的数据只要了**20s** 而在linux中用redis自带的redis-benchmark查询性能 结果

在Node.js应用中读写Redis数据库的简单方法

  这篇文章主要介绍了在Node.js应用中读写Redis数据库的简单方法,Redis是一个内存式高速数据库,需要的朋友可以参考下 在开始本文之前请确保安装好 Redis 和 Node.js 以及 Node.js 的 Redis 扩展 -- node_redis 首先创建一个新文件夹并新建文本文件 app.js 文件内容如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 var redis = require("redis") ,

java项目添加redis缓存的问题

问题描述 java项目添加redis缓存的问题 在给已经上线的java开发项目添加redis缓存时,在往redis添加数据时,要求添加到redis的 db1数据库里面去.但是它默认是添加到db0里面去的,这个怎么解决? 还有在做删除操作的时,是根据key值对缓存数据进行删除操作,但默认还是删除db0里的 数据,怎么让其删除db1的数据? 代码怎么实现?跪求大神们给点指导,谢谢! 解决方案 你连接redis的指定数据库名字就可以了 解决方案二: java缓存问题Redis缓存应用之Java

在Node.js应用中读写Redis数据库的简单方法_node.js

 在开始本文之前请确保安装好 Redis 和 Node.js 以及 Node.js 的 Redis 扩展 -- node_redis 首先创建一个新文件夹并新建文本文件 app.js 文件内容如下:   var redis = require("redis") , client = redis.createClient(); client.on("error", function (err) { console.log("Error " + er

Python读写Redis数据库操作示例_python

使用Python如何操作Redis呢?下面用实例来说明用Python读写Redis数据库.比如,我们插入一条数据,如下: 复制代码 代码如下: import redis class Database:      def __init__(self):          self.host = 'localhost'          self.port = 6379      def write(self,website,city,year,month,day,deal_number):    

Redis主从实现读写分离_Redis

前言 大家在工作中可能会遇到这样的需求,即Redis读写分离,目的是为了压力分散化.下面我将为大家介绍借助AWS的ELB实现读写分离,以写主读从为例. 实现 引用库文件 <!-- redis客户端 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.2</version> &l

mysql-急求:java代码如何实现MySQL数据库的读写(数据库里面有很多表)?谢谢??

问题描述 急求:java代码如何实现MySQL数据库的读写(数据库里面有很多表)?谢谢?? java代码如何实现MySQL数据库的读写(数据库里面有很多表)?在一个程序中可以实现所有数据库中的表都可以进行读写 解决方案 在程序中导入jdbc,数据库驱动的jar包,可以使用JDBC操作数据库,到后面的话,如果接触到连接池,就可以代替下面的代码了.因为连接池还是很方便的.记得要改成你自己的数据库,还有用户名,密码.及sql语句. package cn.itcast.jdbc; import java

php与Redis分页程序代码

用上redis之后速度上去的结果就是操作数据的复杂性了.分页有种脱了裤子放屁的感觉.但是也没有别的办法.代码如下    代码如下 复制代码 <?php $redis = new Redis; $redis->connect('127.0.0.1',6379,0); //数据库 $host='********'; $user='root'; $psd='****'; $dbname='ask';   $link = mysql_connect($host,$user,$psd); mysql_s

redis安装,redis项目以来,redis和spring整合,redis的service,redis的service实现类

一.redis安装: Redis-3.2.6.tar.gz安装,参考方式: 用源码工程来编译安装 1.  到官网下载最新stable版,这里使用的是:redis-3.2.6.tar.gz 2.  cd /usr/local   3.  make redis-src 4.  tar -zxvf    redis-3.2.6.tar.gz  -C  ./redis-src/ 2.解压源码并进入目录cd  /usr/local/redis-src/redis-3.2.6 3. 先执行make,检查是否