SpringCloud缓存服务搭建

搭建公共的Redis服务和公共的Redis调用模块(Feign)

SpringCloud缓存服务搭建_第1张图片

所有的缓存请求统一调用redis微服务,抽取调用redis服务器Feign模块

在这里插入图片描述

搭建微服务

统一由redis微服务去访问redis缓存. 由jedis操作redis

导入的包

   <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-config-clientartifactId>
        dependency>
         
        <dependency>
            <groupId>com.maruigroupId>
            <artifactId>hrm-basic-utilsartifactId>
        dependency>
    dependencies>

jedis 工具类

package com.marui.hrm.util;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Properties;

/**
 * 获取连接池对象
 */
public enum RedisUtils {
     
    INSTANCE;
    static JedisPool jedisPool = null;

    static {
     
        //1 创建连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        //2 进行配置-四个配置
        config.setMaxIdle(1);//最小连接数
        config.setMaxTotal(11);//最大连接数
        config.setMaxWaitMillis(10 * 1000L);//最长等待时间
        config.setTestOnBorrow(true);//测试连接时是否畅通
        //3 通过配置对象创建连接池对象
        Properties properties = null;
        try {
     
            properties = new Properties();
            properties.load(RedisUtils.class.getClassLoader().getResourceAsStream("redis.properties"));
        } catch (IOException e) {
     
            e.printStackTrace();
        }
        String host = properties.getProperty("redis.host");
        String port = properties.getProperty("redis.port");
        String timeout = properties.getProperty("redis.timeout");

        jedisPool = new JedisPool(config, host, Integer.valueOf(port),Integer.valueOf(timeout));
    }

    //获取连接
    public Jedis getSource() {
     
        return jedisPool.getResource();
    }

    //关闭资源
    public void closeSource(Jedis jedis) {
     
        if (jedis != null) {
     
            jedis.close();
        }

    }

    /**
     * 设置字符值
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
     
        Jedis jedis = getSource();
        jedis.set(key, value);
        closeSource(jedis);
    }

    /**
     * 设置
     * @param key
     * @param value
     */
    public void set(byte[] key, byte[] value) {
     
        Jedis jedis = getSource();
        jedis.set(key, value);
        closeSource(jedis);
    }

    /**
     *
     * @param key
     * @return
     */
    public byte[]  get(byte[] key) {
     
        Jedis jedis = getSource();
        try {
     
            return jedis.get(key);
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            closeSource(jedis);
        }
        return null;

    }

    /**
     * 设置字符值
     *
     * @param key
     */
    public String get(String key) {
     
        Jedis jedis = getSource();
        try {
     
            return jedis.get(key);
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            closeSource(jedis);
        }
        return null;
    }
}

jedis的配置文件

redis.host=127.0.0.1
redis.port=6379
redis.timeout=5000

Controller接口

package com.marui.hrm.web.controller;

import com.marui.hrm.util.AjaxResult;
import com.marui.hrm.util.RedisUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Auther: Little Pig
 * @Date: 2020/1/2 17:34
 * @Description: 这个控制器操作负责操作redis
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
     

    @GetMapping("/set")
    public AjaxResult set(@RequestParam("key") String key, @RequestParam("value") String value) {
     
        try {
     
            RedisUtils.INSTANCE.set(key, value);
            return AjaxResult.me().setSuccess(true).setMessage("操作成功").setResultObj(value);
        } catch (Exception e) {
     
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setResultObj(null);
        }
    }

    @PostMapping("/get/{key}")
    public AjaxResult get(@PathVariable String key) {
     
        try {
     
            String result = RedisUtils.INSTANCE.get(key);
            if (result != null) {
     
                return AjaxResult.me().setMessage("操作成功").setSuccess(true).setResultObj(result);
            }else {
     
                return AjaxResult.me().setMessage("操作成功").setSuccess(false).setResultObj(null);
            }
        } catch (Exception e) {
     
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage()).setSuccess(false).setResultObj(null);
        }
    }
}

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @Auther: Little Pig
 * @Date: 2019/12/30 22:18
 * @Description:
 */
@SpringBootApplication
@EnableEurekaClient
public class RedisService4010Application {
     

    public static void main(String[] args) {
     
        SpringApplication.run(RedisService4010Application.class);
    }
}

调用这个微服务接口

@FeignClient(name = "redis-server",fallback = HystrixClientFallback.class)
public interface RedisClient {
     

    @RequestMapping(value = "/redis/set",method = RequestMethod.GET)
    AjaxResult set(@RequestParam("key") String key, @RequestParam("value") String value);

    @RequestMapping(value = "/redis/get/{key}",method = RequestMethod.POST)
    AjaxResult get(@PathVariable String key);

}

course-server的service层调用redis微服务

package com.marui.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.marui.hrm.domain.CourseType;
import com.marui.hrm.feign_client.RedisClient;
import com.marui.hrm.mapper.CourseTypeMapper;
import com.marui.hrm.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.marui.hrm.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 

* 课程目录 服务实现类 *

* * @author marui * @since 2019-12-31 */
@Service public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService { private final String COURSE_TYPE = "course_type"; @Autowired private RedisClient redisClient; @Override public List<CourseType> getTreeData() { return getDataFromRedis(); } /** * 向redis中请求缓存的方法 * @return */ private List<CourseType> getDataFromRedis() { // 先向缓存中查询 AjaxResult ajaxResult = redisClient.get(COURSE_TYPE); // 如果redis宕机,返回托底数据 if (ajaxResult.getMessage().equals("保存出错,我们正在殴打程序员")){ return new ArrayList<>(); } if (! ajaxResult.isSuccess() && ajaxResult.getResultObj() == null) { // 向数据库中查询 List<CourseType> courseById = baseMapper.getCourseById(0L); // 设置到redis中 redisClient.set(COURSE_TYPE, JSON.toJSONString(courseById)); return courseById; }else { // 如果redis中有缓存就返回 List<CourseType> courseTypes = JSON.parseArray(ajaxResult.getResultObj().toString(), CourseType.class); return courseTypes; } } /** * 设置 CourseType的Path * @param entity * @return */ @Override public boolean insert(CourseType entity) { // 保存主键后拿到id boolean insert = super.insert(entity); System.out.println("对象的id"+entity.getId()); CourseType temp = entity; StringBuffer sb = new StringBuffer(entity.getId().toString()); while (!Long.valueOf(0L).equals(temp.getPid())) { Long pid = temp.getPid(); sb.insert(0,".").insert(0, pid.toString()); temp = baseMapper.selectById(pid); } entity.setPath(sb.toString()); boolean update = updateById(entity); return insert && update; } /** * 修改,新增,删除,更新Redis缓存 * @param entity * @return */ @Override public boolean updateById(CourseType entity) { boolean b = super.updateById(entity); if (b) { // 更新redis redisClient.set(COURSE_TYPE, JSON.toJSONString(baseMapper.getCourseById(0L))); } return b; } @Override public boolean deleteById(Serializable id) { boolean b = super.deleteById(id); if (b) { // 更新redis redisClient.set(COURSE_TYPE, JSON.toJSONString(baseMapper.getCourseById(0L))); } return b; } }

你可能感兴趣的:(SpringCloud)