概述
要使用redis先得 在windows或者linux服务器中去安装redis,然后启动redis-server 这是前提条件 这一步就不累述了
========================================================================================
标准的maven项目 第一步 先在 pom.xml中引入redis的jar包
建一个Config.properties文件 存储redis的一些配置
再建一个 RedisUtil 用来写一些代码中需要调用的一些方法 ,例如 连接 加载 以及释放资源
public class RedisUtil {
private static ResourceBundle prop = ResourceBundle.getBundle("Config");
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);
//Redis服务器IP
private static String ADDR = getRedisProp("REDIS_ADDR");
//Redis的端口号 port 6380 for test. 6379 for normal
private static int PORT = Integer.parseInt(getRedisProp("REDIS_PORT"));
//访问密码
private static String AUTH = getRedisProp("REDIS_AUTH");
private static int DATABASE_NUMBER = Integer.parseInt(getRedisProp("REDIS_DATABASE_NUMBER"));
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 500;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 10000;
private static int TIMEOUT = 10000;
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
private static ScanParams sp = new ScanParams();
public static String getADDR() {
return ADDR;
}
public static void setADDR(String aDDR) {
ADDR = aDDR;
}
public static int getPORT() {
return PORT;
}
public static void setPORT(int pORT) {
PORT = pORT;
}
public static String getAUTH() {
return AUTH;
}
public static void setAUTH(String aUTH) {
AUTH = aUTH;
}
public static int getMAX_ACTIVE() {
return MAX_ACTIVE;
}
public static void setMAX_ACTIVE(int mAX_ACTIVE) {
MAX_ACTIVE = mAX_ACTIVE;
}
public static int getMAX_IDLE() {
return MAX_IDLE;
}
public static void setMAX_IDLE(int mAX_IDLE) {
MAX_IDLE = mAX_IDLE;
}
public static int getMAX_WAIT() {
return MAX_WAIT;
}
public static void setMAX_WAIT(int mAX_WAIT) {
MAX_WAIT = mAX_WAIT;
}
public static int getTIMEOUT() {
return TIMEOUT;
}
public static void setTIMEOUT(int tIMEOUT) {
TIMEOUT = tIMEOUT;
}
public static boolean isTEST_ON_BORROW() {
return TEST_ON_BORROW;
}
public static void setTEST_ON_BORROW(boolean tEST_ON_BORROW) {
TEST_ON_BORROW = tEST_ON_BORROW;
}
/**
* 初始化Redis连接池
*/
// static {
// try {
// JedisPoolConfig config = new JedisPoolConfig();
// config.setMaxActive(MAX_ACTIVE);
// config.setMaxIdle(MAX_IDLE);
// config.setMaxWait(MAX_WAIT);
// config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);//现在是无密码连接
// jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
public static void reload(){
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(MAX_IDLE);
config.setMinIdle(20);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
//最大连接数, 应用自己评估,不要超过ApsaraDB for Redis每个实例最大的连接数
config.setMaxTotal(2000);
config.setTestOnBorrow(false);
config.setTestOnReturn(false);
LOGGER.debug("【redis缓存服务器URL】:"+ADDR+",连接成功");
if(StringUtil.isStrNotNullAndNotEmpty(AUTH)){
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH, DATABASE_NUMBER);
}else{
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("【redis缓存服务器URL】:"+ADDR+",连接失败");
}
}
//
/**
* 获取Jedis实例
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool == null) {
reload();
}
return jedisPool.getResource();
} catch (Exception e) {
LOGGER.error("redis 初始化异常", e);
return null;
}
}
/**
* 释放jedis资源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
*获取redis配置信息
* @param redisConfig
*/
public synchronized static String getRedisProp(String redisConfig) {
String result = null;
try {
result = prop.getString(redisConfig);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Description: 通过字符串匹配扫描redis并且返回keys集合,如果match为null则返回所有结果
* @param: jedis, match
* @return: resultList
*/
//TODO: 目前暂时用不到所以改为private方法
public static List<String> scanRedisByMatch(String match){
Jedis jedis = getJedis();
ScanResult<String> ret = null;
if (match != null){
sp.match(match);
sp.count(1000);
// 默认数据库为0
ret = jedis.scan(0, sp);
} else {
ret = jedis.scan(0);
}
List<String> resultList = ret.getResult();
jedis.close();
return resultList;
}
/**
* Description: 删除相应的keys
* @param: jedis, keys
* @return:
*/
//TODO: 目前暂时用不到所以改为private方法
private static void delByKeys(List<String> keys){
Jedis jedis = getJedis();
for (String key : keys) {
jedis.del(key);
}
jedis.close();
}
/**
* Description: 将制定keys的数据存放到指定DBIndex的redis数据库中
* @param: jedis keys DBIndex
* @return:
*/
//TODO: 目前暂时用不到所以改为private方法
private static void moveByKeys(List<String> keys, int DBIndex) {
Jedis jedis = getJedis();
for (String key : keys) {
jedis.move(key, DBIndex);
}
jedis.close();
}
下面是一些使用
public ResultDto aroundService(ProceedingJoinPoint joinPoint) throws Throwable {
logger.debug("Service层around开始");
Object[] args = joinPoint.getArgs();
String methodName = joinPoint.getSignature().getName();
String params = "";
for(Object o :args){
params+=o.toString();
}
boolean flag = false;
ResultDto result = new ResultDto();
Jedis jedis = RedisUtil.getJedis();
ObjectTranscoder<ResultDto> objTranscoder = new ObjectTranscoder<ResultDto>();
if (StringUtil.isObjNotNull(jedis)) {
byte[] bytelist = jedis.get((methodName+params).getBytes());
if (StringUtil.isObjNotNull(bytelist)) {
result = objTranscoder.deserialize(bytelist);
flag = true;
logger.debug("Service层around,获取"+methodName+params+"缓存成功");
}
}
RedisUtil.returnResource(jedis);
if(flag ==false){
// 继续执行这个接口,没有这句会被卡住
result = (ResultDto)joinPoint.proceed(args);
if (flag == false) {
jedis = RedisUtil.getJedis();
if (StringUtil.isObjNotNull(jedis)) {
jedis.set((methodName+params).getBytes(),
objTranscoder.serialize(result));
}
RedisUtil.returnResource(jedis);
}
}
logger.debug("Service层around结束");
return result;
}
public ResultDto loadCache(){
if(isLoadCache){
return ResultDtoFactory.toNack("加载缓存方法运行中,请不要重复点击。");
}
try {
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
isLoadCache = true;
//用线程来加载缓存
logger.info("开始清除缓存");
Jedis jedis = RedisUtil.getJedis();//缓存打开
//将**首页的5个策略先拿出
storeZhiyuOptimize(jedis);
jedis.flushDB();
logger.info("缓存清除成功");
RedisUtil.returnResource(jedis);//缓存关闭
//加载首页,判断如果有一个策略的结果为空,则用旧数据覆盖新数据
if (((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getInvestmentRatingAndQuarterGrowthTable().getData()).size() == 0
|| ((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getHighMoatTable().getData()).size() == 0
|| ((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getInvestmentRatingChangeFactorTable().getData()).size() == 0
|| ((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getDailyAverageAndHighMoatTable().getData()).size() == 0
|| ((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getHighMoatTableAndInvestmentRatingTable().getData()).size() == 0
||((List<ZhiyuOptimizeDto>)zhiyuOptimizeService.getMoatGrowthTable().getData()).size() == 0){
Jedis jedis1 = RedisUtil.getJedis();
ObjectTranscoder<ResultDto> objTranscoder = new ObjectTranscoder<ResultDto>();
jedis1.set("getInvestmentRatingAndQuarterGrowthTable".getBytes(), objTranscoder.serialize(redisInvestmentRatingAndQuarterGrowthTable));
jedis1.set("getHighMoatTable".getBytes(), objTranscoder.serialize(redisHighMoatTable));
jedis1.set("getInvestmentRatingChangeFactorTable".getBytes(), objTranscoder.serialize(redisInvestmentRatingChangeFactorTable));
jedis1.set("getDailyAverageAndHighMoatTable".getBytes(), objTranscoder.serialize(redisDailyAverageAndHighMoatTable));
jedis1.set("getHighMoatTableAndInvestmentRatingTable".getBytes(), objTranscoder.serialize(redisHighMoatTableAndInvestmentRatingTable));
jedis1.set("getMoatGrowthTable".getBytes(), objTranscoder.serialize(redisMoatGrowthTable));
RedisUtil.returnResource(jedis1);
}
//加载**相关
stockPoolService.getStockPoolDetail("1");
//加载所有策略的最近一个月持仓情况
// modelService.loadAllModelHoldPositionInfo();
//获取最近一个月的交易日日期list
List<String> trandingDayList = otherDao.findLastMonthTrandDay(DateUtil.getDateString10(new Date()));
//获取所有策略idlist
List<ModelDto> modelDtoList = modelDao.getAllStrategicIncome();
//循环调用获取持仓信息的方法 以及调仓信息
for (ModelDto model:modelDtoList) {
for (String day:trandingDayList) {
modelService.getHoldPositionInfo(model.getId().toString(),day);
modelService.getAdjustPositionInfoNF(model.getId().toString(),day);
}
}
//行业监控相关
IndustryPriceDto dto = new IndustryPriceDto();
dto.setClassLevel("1");
dto.setSwCodeLevel1("0");
dto.setType("1");
industryFactorService.getCHGpct(dto);
logger.info("行业监控缓存加载成功");
List<String> industrylist = otherDao.getAllIndustry();
logger.info("开始加载行业股票对应关系");
for (String industry : industrylist) {
logger.info("线程加载中====================行业股票对应关系:" + industry);
industryFactorService.getStockCompare(industry);
}
logger.info("行业股票对应关系加载完成");
isLoadCache = false;
}
});
t.start();
}
return ResultDtoFactory.toAck("缓存加载成功");
} catch (Exception e) {
e.printStackTrace();
return ResultDtoFactory.toNack("缓存加载失败");
}
}
最后
以上就是痴情月亮为你收集整理的Java代码中对redis的使用的全部内容,希望文章能够帮你解决Java代码中对redis的使用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复