Redis

Redis,第1张

Redis
pom.xml依赖:
  
     org.springframework.boot
      spring-boot-starter-data-redis
  
    appliaction.yml:
        redis:
	    database: 0
	    host: localhost
	    port: XXXX
	    password:
	    jedis:
	      pool:
	        max-active: 100
	        max-idle: 3
	        max-wait: -1
	        min-idle: 0
	    timeout: 1000
Redis实现类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class RedisService {
    @Autowired
    private RedisTemplate redisTemplate;


    
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }


    

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.HOURS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

}
需要缓存的serviceImpl:
public JSonObject get(Integer id) {
    JSonObject jsonObject = new JSonObject();
    if(redisService.keyExists("eip-home-content") && redisService.get("eip-home-content") != null){
        jsonObject.put("result", redisService.get("eip-home-content"));
        jsonObject.put("message", "首页的栏目信息获取成功!");
        logger.info("缓存首页的栏目信息获取成功!");
        return jsonObject;
    }
    //获取信息
    List XXXList=XXXMapper.selectByPrimaryKey(id);
    AriticleResponseDto groupingCategory= GroupingUtil.grouping(oldeipCategory).get(0);
    if(XXXList.size()<0){
        jsonObject.put("code", 400);
        jsonObject.put("message", "信息获取失败!");
        logger.error("信息获取失败!");
        return jsonObject;
    }
    redisService.set("eip-home-content",groupingCategory,1);
    jsonObject.put("result", groupingCategory);
    jsonObject.put("message", "信息获取成功!");
    logger.info("信息获取成功!");
    return jsonObject;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4997892.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存