大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
要想在Java中连接Redis,并进行操作,由两种方式,一种是spring data redis,它是由spring集成的,不支持集群,一种是官方推荐的jedis,支持集群,其他功能差不多一样,
这里我们介绍jedis操作实例,以下是使用Jedis的具体步骤:
1、如果是在Maven项目中,在pom.xml中增加如下语句,如果不是Maven项目下载包导入项目即可:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.2</version>
</dependency>
2、创建redis.properties配置文件,设置连接参数
# Redis settings
redis.host=192.168.0.240
redis.port=6379
redis.pass=xxxxxx
redis.timeout=10000
redis.maxIdle=300
redis.maxTotal=600
# 毫秒
redis.maxWaitMillis=1000
redis.testOnBorrow=false
3、创建属性文件加载工具类,用于获取redis.properties文件
package com.rmd.cart.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 属性文件加载工具类
* @author lc
*/
public class PropertyUtil {
//加载property文件到io流里面
public static Properties loadProperties(String propertyFile) {
Properties properties = new Properties();
try {
InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
if(is == null){
is = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/" + propertyFile);
}
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
/**
* 根据key值取得对应的value值
*
* @param key
* @return
*/
public static String getValue(String propertyFile, String key) {
Properties properties = loadProperties(propertyFile);
return properties.getProperty(key);
}
}
4、创建连接redis工具类
package com.rmd.cart.utils;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* redis工具类
* @author lc
*/
public class JedisUtil {
private static JedisPool jedisPool = null;
private JedisUtil() {
}
//写成静态代码块形式,只加载一次,节省资源
static {
Properties properties = PropertyUtil.loadProperties("redis.properties");
String host = properties.getProperty("redis.host");
String port = properties.getProperty("redis.port");
String pass = properties.getProperty("redis.pass");
String timeout = properties.getProperty("redis.timeout");
String maxIdle = properties.getProperty("redis.maxIdle");
String maxTotal = properties.getProperty("redis.maxTotal");
String maxWaitMillis = properties.getProperty("redis.maxWaitMillis");
String testOnBorrow = properties.getProperty("redis.testOnBorrow");
JedisPoolConfig config = new JedisPoolConfig();
//控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(Integer.parseInt(maxTotal));
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
config.setMaxIdle(Integer.parseInt(maxIdle));
//表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
config.setTestOnBorrow(Boolean.valueOf(testOnBorrow));
jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), pass);
}
/**
* 从jedis连接池中获取获取jedis对象
*
* @return
*/
private Jedis getJedis() {
return jedisPool.getResource();
}
private static final JedisUtil jedisUtil = new JedisUtil();
/**
* 获取JedisUtil实例
*
* @return
*/
public static JedisUtil getInstance() {
return jedisUtil;
}
/**
* 回收jedis(放到finally中)
*
* @param jedis
*/
private void returnJedis(Jedis jedis) {
if (null != jedis && null != jedisPool) {
jedisPool.returnResource(jedis);
}
}
/**
* 销毁连接(放到catch中)
*
* @param jedis
*/
private static void returnBrokenResource(Jedis jedis) {
if (null != jedis && null != jedisPool) {
jedisPool.returnResource(jedis);
}
}
/**
* 添加sorted set
*
* @param key
* @param value
* @param score
*/
public void zadd(String key, String value, double score) {
Jedis jedis = getJedis();
jedis.zadd(key, score, value);
returnJedis(jedis);
}
/**
* 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zrange(String key, int start, int end) {
Jedis jedis = getJedis();
Set<String> set = jedis.zrange(key, start, end);
returnJedis(jedis);
return set;
}
/**
* 获取给定区间的元素,原始按照权重由高到低排序
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zrevrange(String key, int start, int end) {
Jedis jedis = getJedis();
Set<String> set = jedis.zrevrange(key, start, end);
returnJedis(jedis);
return set;
}
/**
* 添加对应关系,如果对应关系已存在,则覆盖
*
* @param key
* @param map 对应关系
* @return 状态,成功返回OK
*/
public String hmset(String key, Map<String, String> map) {
Jedis jedis = getJedis();
String s = jedis.hmset(key, map);
returnJedis(jedis);
return s;
}
/**
* 向List头部追加记录
*
* @param key
* @param value
* @return 记录总数
*/
public long rpush(String key, String value) {
Jedis jedis = getJedis();
long count = jedis.rpush(key, value);
returnJedis(jedis);
return count;
}
/**
* 向List头部追加记录
*
* @param key
* @param value
* @return 记录总数
*/
private long rpush(byte[] key, byte[] value) {
Jedis jedis = getJedis();
long count = jedis.rpush(key, value);
returnJedis(jedis);
return count;
}
/**
* 删除
*
* @param key
* @return
*/
public long del(String key) {
Jedis jedis = getJedis();
long s = jedis.del(key);
returnJedis(jedis);
return s;
}
/**
* 从集合中删除成员
* @param key
* @param value
* @return 返回1成功
* */
public long zrem(String key, String... value) {
Jedis jedis = getJedis();
long s = jedis.zrem(key, value);
returnJedis(jedis);
return s;
}
public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)
throws Exception {
Jedis jedis = null;
boolean isBroken = false;
try {
jedis = getJedis();
jedis.select(dbIndex);
jedis.set(key, value);
if (expireTime > 0)
jedis.expire(key, expireTime);
} catch (Exception e) {
isBroken = true;
throw e;
} finally {
returnResource(jedis, isBroken);
}
}
public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
Jedis jedis = null;
byte[] result = null;
boolean isBroken = false;
try {
jedis = getJedis();
jedis.select(dbIndex);
result = jedis.get(key);
} catch (Exception e) {
isBroken = true;
throw e;
} finally {
returnResource(jedis, isBroken);
}
return result;
}
public void deleteByKey(int dbIndex, byte[] key) throws Exception {
Jedis jedis = null;
boolean isBroken = false;
try {
jedis = getJedis();
jedis.select(dbIndex);
jedis.del(key);
} catch (Exception e) {
isBroken = true;
throw e;
} finally {
returnResource(jedis, isBroken);
}
}
public void returnResource(Jedis jedis, boolean isBroken) {
if (jedis == null)
return;
if (isBroken)
jedisPool.returnBrokenResource(jedis);
else
jedisPool.returnResource(jedis);
}
/**
* 获取总数量
* @param key
* @return
*/
public long zcard(String key) {
Jedis jedis = getJedis();
long count = jedis.zcard(key);
returnJedis(jedis);
return count;
}
/**
* 是否存在KEY
* @param key
* @return
*/
public boolean exists(String key) {
Jedis jedis = getJedis();
boolean exists = jedis.exists(key);
returnJedis(jedis);
return exists;
}
/**
* 重命名KEY
* @param oldKey
* @param newKey
* @return
*/
public String rename(String oldKey, String newKey) {
Jedis jedis = getJedis();
String result = jedis.rename(oldKey, newKey);
returnJedis(jedis);
return result;
}
/**
* 设置失效时间
* @param key
* @param seconds
*/
public void expire(String key, int seconds) {
Jedis jedis = getJedis();
jedis.expire(key, seconds);
returnJedis(jedis);
}
/**
* 删除失效时间
* @param key
*/
public void persist(String key) {
Jedis jedis = getJedis();
jedis.persist(key);
returnJedis(jedis);
}
/**
* 添加一个键值对,如果键存在不在添加,如果不存在,添加完成以后设置键的有效期
* @param key
* @param value
* @param timeOut
*/
public void setnxWithTimeOut(String key,String value,int timeOut){
Jedis jedis = getJedis();
if(0!=jedis.setnx(key, value)){
jedis.expire(key, timeOut);
}
returnJedis(jedis);
}
/**
* 返回指定key序列值
* @param key
* @return
*/
public long incr(String key){
Jedis jedis = getJedis();
long l = jedis.incr(key);
returnJedis(jedis);
return l;
}
/**
* 获取当前时间
* @return 秒
*/
public long currentTimeSecond(){
Long l = 0l;
Jedis jedis = getJedis();
Object obj = jedis.eval("return redis.call('TIME')",0);
if(obj != null){
List<String> list = (List)obj;
l = Long.valueOf(list.get(0));
}
returnJedis(jedis);
return l;
}
}
5、编写redis服务类
package com.rmd.cart.service.impl;
import java.util.Date;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.rmd.cart.utils.JedisUtil;
/**
* redis服务
* @author lc
*/
@Service("redisService")
public class RedisService {
/**
* 添加SortSet型数据
* @param key
* @param value
*/
public void addSortSet(String key, String value) {
double score = new Date().getTime();
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.zadd(key, value, score);
}
/**
* 获取倒序的SortSet型的数据
* @param key
* @return
*/
public Set<String> getDescSortSet(String key) {
JedisUtil jedisUtil = JedisUtil.getInstance();
return jedisUtil.zrevrange(key, 0, -1);
}
/**
* 删除SortSet型数据
* @param key
* @param value
*/
public void deleteSortSet(String key, String value) {
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.zrem(key, value);
}
/**
* 批量删除SortSet型数据
* @param key
* @param value
*/
public void deleteSortSetBatch(String key, String[] value) {
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.zrem(key, value);
}
/**
* 范围获取倒序的SortSet型的数据
* @param key
* @return
*/
public Set<String> getDescSortSetPage(String key,int start, int end) {
JedisUtil jedisUtil = JedisUtil.getInstance();
return jedisUtil.zrevrange(key, start, end);
}
/**
* 获取SortSet型的总数量
* @param key
* @return
*/
public long getSortSetAllCount(String key) {
JedisUtil jedisUtil = JedisUtil.getInstance();
return jedisUtil.zcard(key);
}
/**
* 检查KEY是否存在
* @param key
* @return
*/
public boolean checkExistsKey(String key) {
JedisUtil jedisUtil = JedisUtil.getInstance();
return jedisUtil.exists(key);
}
/**
* 重命名KEY
* @param oldKey
* @param newKey
* @return
*/
public String renameKey(String oldKey, String newKey) {
JedisUtil jedisUtil = JedisUtil.getInstance();
return jedisUtil.rename(oldKey, newKey);
}
/**
* 删除KEY
* @param key
*/
public void deleteKey(String key) {
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.del(key);
}
/**
* 设置失效时间
* @param key
* @param seconds 失效时间,秒
*/
public void setExpireTime(String key, int seconds) {
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.expire(key, seconds);
}
/**
* 删除失效时间
* @param key
*/
public void deleteExpireTime(String key) {
JedisUtil jedisUtil = JedisUtil.getInstance();
jedisUtil.persist(key);
}
}
注意:以上是公共基础,下面是我业务操作,怎样保存数据和获取数据
6、由于我想做购物车,创建购物车service接口,代码如下
package com.rmd.cart.service;
import java.util.Set;
/**
* @Description: 购物车service
* @author lc
*/
public interface CartService {
/**
*
* @Description: 添加购物车
* @author lc
* @param customerId
* void
*/
public void add(String customerId);
/**
* @Description: 获取购物车数据
* @author lc
* @param customerId
* @return
* Set<String>
*/
public Set<String> getCart(String customerId);
}
7、创建impl类实现service接口,代码如下
package com.rmd.cart.service.impl;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rmd.cart.service.CartService;
@Service("cartService")
public class CartServiceImpl implements CartService {
@Autowired
private RedisService redisService;
@Override
public void add(String customerId) {
redisService.addSortSet("rmd_cart_test123", customerId);
}
@Override
public Set<String> getCart(String customerId) {
return redisService.getDescSortSet("rmd_cart_test123");
}
}
8、创建一个对象类,用户数据测试
package com.rmd.cart.bean;
import java.io.Serializable;
import java.util.List;
public class SpuInfo implements Serializable{
private Integer spuid;//spuid
private long createTime;//添加时间
private List<SkuInfo> skuList;//sku信息集合
public Integer getSpuid() {
return spuid;
}
public void setSpuid(Integer spuid) {
this.spuid = spuid;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public List<SkuInfo> getSkuList() {
return skuList;
}
public void setSkuList(List<SkuInfo> skuList) {
this.skuList = skuList;
}
}
9、创建测试类,使用junit4进行测试
添加数据
package rmd_cart_provider.service.test;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import javax.annotation.Resource;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.rmd.cart.bean.SpuInfo;
import com.rmd.cart.service.CartService;
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration({"/applicationContext.xml"}) //加载配置文件
public class CartTest {
@Resource
private CartService cartService;
@Test
public void test() throws JsonGenerationException, JsonMappingException, IOException{
SpuInfo spu = new SpuInfo();
spu.setSpuid(123);
spu.setCreateTime(105456464);
//将对象转换成json字符串
ObjectMapper om = new ObjectMapper();
Writer wr = new StringWriter();
om.writeValue(wr, spu);
String str = wr.toString();
//添加数据
cartService.add(str);
}
}
获取数据
package rmd_cart_provider.service.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.rmd.cart.bean.SpuInfo;
import com.rmd.cart.service.CartService;
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration({"/applicationContext.xml"}) //加载配置文件
public class CartTest {
@Resource
private CartService cartService;
@Test
public void test() throws JsonGenerationException, JsonMappingException, IOException{
//获取数据
List<SpuInfo> spuList = new ArrayList<>();
ObjectMapper om = new ObjectMapper();
//转回对象
Set<String> set = cartService.getCart(null);
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String value = iterator.next();
SpuInfo spuVo = om.readValue(value, SpuInfo.class);
spuList.add(spuVo);
}
}
}
上面添加和获取数据的时候用到了JUnit4和ObjectMapper
JUnit4单元测试,这个应该都知道,只要加入包就行
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
ObjectMapper这个是一个高效的对象和json之间转换的类,具体方法查文档,谁用都说好,推荐给大家
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
以上是个人在学习和做项目中用到的东西,记录一下,如有更好的建议一起研究学习
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/195633.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...