【springcloud】微服务中拆分出redis

1. 写在前面

最近的项目中遇到的问题,本来想将redis不写成服务而是简单用作工具类用maven坐标方式引进其他服务中,但是 jedis = jedisPool.getResource() 这行代码中获取 jedis 连接一直报空指针异常。然后又去换了 boot中提供的RedisTemplate对象去操作,然而RedisTemplate对象也是空,博主认为是不同的项目中使用会产生不同的spring容器,而在不同的容器中拿对象肯定拿不到,网上百度各种方法没有找到,不得已写成服务的形式来调用。

2. 建立eureka服务项目
2.1. pom.xml

<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
		<java.version>1.8java.version>
		<spring-cloud.version>Finchley.RELEASEspring-cloud.version>
	properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>

		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
		dependency>

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-devtoolsartifactId>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

	
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloudgroupId>
				<artifactId>spring-cloud-dependenciesartifactId>
				<version>${spring-cloud.version}version>
				<type>pomtype>
				<scope>importscope>
			dependency>
		dependencies>
	dependencyManagement>

	
	<repositories>
		<repository>
			<id>spring-milestonesid>
			<name>Spring Milestonesname>
			<url>https://repo.spring.io/milestoneurl>
			<snapshots>
				<enabled>falseenabled>
			snapshots>
		repository>
	repositories>

2.2. application.yml

server:
  port: 7001

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:7001/eureka/

2.3. 启动类上添加注解 @EnableEurekaServer

3. reids 服务提供项目
3.1. pom.xml

<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
		<java.version>1.8java.version>
		<junit.version>4.12junit.version>
		<spring-cloud.version>Finchley.RELEASEspring-cloud.version>
	properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-redisartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-cacheartifactId>
		dependency>

		
		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-configartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-openfeignartifactId>
		dependency>

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-devtoolsartifactId>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

	
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloudgroupId>
				<artifactId>spring-cloud-dependenciesartifactId>
				<version>${spring-cloud.version}version>
				<type>pomtype>
				<scope>importscope>
			dependency>
		dependencies>
	dependencyManagement>

	<repositories>
		<repository>
			<id>spring-milestonesid>
			<name>Spring Milestonesname>
			<url>https://repo.spring.io/milestoneurl>
			<snapshots>
				<enabled>falseenabled>
			snapshots>
		repository>
	repositories>

3.2. application.yml

# 端口配置
server:
  port: 8761

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    instance-id: springcloud-redis-8761   # 修改主机名称(区别于服务名称)
    prefer-ip-address: true

#redis配置
spring:
  application:
    name: service-redis  # 服务名字
  redis:
    host: 127.0.0.1           # 服务器地址
    port: 6379                # 服务端口号
    database: 0               # 数据库索引
    password:                 # 服务器连接密码默认为空
    jedis:
      pool:
        max-active: 50  # 连接池最大连接数
        max-wait: 3000  # 连接池最大阻塞等待时间
        max-idle: 20    # 连接池中最大的空闲连接
        min-idle: 2     # 连接池中最小的空闲连接
    timeout: 5000       # 连接超时时间

3.3. redis 服务提供者

import java.util.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisUtils {

    /**日志记录器*/
    Logger log = Logger.getLogger(RedisUtils.class);
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // ===============统一操作============

    /**
     * @param key
     * @param time
     * @return boolean
     * @throws
     * @description 指定缓存失效时间
     * @author 梁XL
     * @date 2019/4/15
     */
    @PostMapping("/expire")
    public boolean expire(@RequestParam("key") String key,@RequestParam("time") long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * @param key
     * @return boolean
     * @throws
     * @description 判断key是否存在
     * @author 梁XL
     * @date 2019/4/15
     */
    @PostMapping("/hasKey")
    public boolean hasKey(@RequestParam("key") String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key
     * @return void
     * @throws
     * @description 删除一个或多个键
     * @author 梁XL
     * @date 2019/4/15
     */
    @PostMapping("/delete")
    public void delete(@RequestBody String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }

    }

    // ==================String================

    /**
     * @param key
     * @return java.lang.String
     * @throws
     * @description 获取值
     * @author 梁XL
     * @date 2019/4/15
     */
    @PostMapping("/getStr")
    public String getStr(@RequestParam("key") final String key) {
        if (key==null){
            return  null;
        }
        String value=String.valueOf(redisTemplate.opsForValue().get(key));
        return value;
    }

    /**
     * @param key
     * @param value
     * @return boolean
     * @throws
     * @description 设置缓存
     * @author 梁XL
     * @date 2019/4/10
     */
    @PostMapping("/setStr")
    public boolean setStr(@RequestParam("key") final String key,@RequestParam("value") final String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param key
     * @param value
     * @param timeOut
     * @return boolean
     * @throws
     * @description 写入缓存带失效时间
     * @author 梁XL
     * @date 2019/4/10
     */
    @PostMapping("/setStrWithTime")
    public boolean setStrWithTime(@RequestParam("key") final String key,@RequestParam("value") final String value,@RequestParam("timeOut") final long timeOut) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value, timeOut, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 更新缓存
     */
    @PostMapping("/updateStr")
    public boolean getAndSetStr(@RequestParam("key") final String key,@RequestParam("value") final String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // =========================map====================

    /**
     * @description hashGet 获取单条
     * @author 梁XL
     * @date 2019/4/15
     * @param key
     * @param item
     * @return java.lang.Object
     * @throws
     */
    @PostMapping("/hget")
    public Object hget(@RequestParam("key") String key,@RequestParam("item") String item) {
        String result =String.valueOf(redisTemplate.opsForHash().get(key, item));
        return result;
    }

    /**
     * @description 获取hashKey对应的所有键值
     * @author 梁XL
     * @date 2019/4/15
     * @param key
     * @return java.util.Map
     * @throws
     */
    @PostMapping("/hmget")
    public Map<String, Object> hmget(@RequestParam("key") String key) {
        Map<String,Object> resultMap = new HashMap<>();

        Map<Object, Object> redisMap = redisTemplate.opsForHash().entries(key);
        Set<Map.Entry<Object, Object>> entries = redisMap.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            String newKey = String .valueOf(entry.getKey());
            Object value = entry.getValue();
            resultMap.put(newKey , value);
        }

        return resultMap;
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    @PostMapping("/hmset")
    public boolean hmset(@RequestParam("key") String key,@RequestBody Map<Object, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    @PostMapping("/hmsetWithTime")
    public boolean hmsetWithTime(@RequestParam("key") String key,@RequestBody Map<String, Object> map,@RequestParam("time") long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    @PostMapping("/hset")
    public boolean hset(@RequestParam("key") String key,@RequestParam("item") String item,@RequestParam("value") Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    @PostMapping("/hsetWithTime")
    public boolean hsetWithTime(@RequestParam("key") String key,@RequestParam("item") String item,@RequestParam("value") Object value,@RequestParam("time") long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    @PostMapping("/hdel")
    public void hdel(@RequestParam("key") String key,@RequestBody Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    @PostMapping("/hasHashKey")
    public boolean hasHasKey(@RequestParam("key") String key,@RequestParam("item") String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    @PostMapping("/hincr")
    public double hincr(@RequestParam("key") String key,@RequestParam("item") String item,@RequestParam("by") double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    @PostMapping("/hdecr")
    public double hdecr(@RequestParam("key") String key,@RequestParam("item") String item,@RequestParam("by") double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    //============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    @PostMapping("/sGet")
    public Set<Object> sGet(@RequestParam("key") String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    @PostMapping("/sHasKey")
    public boolean sHasKey(@RequestParam("key") String key,@RequestParam("value") Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @PostMapping("/sSet")
    public long sSet(@RequestParam("key") String key,@RequestBody Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @PostMapping("/sSetAndTime")
    public long sSetAndTime(@RequestParam("key") String key,@RequestParam("time") long time,@RequestBody Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    @PostMapping("/sGetSetSize")
    public long sGetSetSize(@RequestParam("key") String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    @PostMapping("/setRemove")
    public long setRemove(@RequestParam("key") String key,@RequestBody Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }
    /**
     * 移除值为value的
     *
     * @param key    键
     * @param value 值
     * @return
     */
    @PostMapping("/Srem")
    public Boolean Srem(@RequestParam("key") String key,@RequestParam("value") String value) {
        boolean result  = false;
        try {
             Object objectValue= value;
             redisTemplate.opsForSet().remove(key, objectValue);
            result=true;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("key:"+key+"===="+"value:"+value+"移除失败");
            return result;
        }

    }

    /**
     * @param key,value
     * @return boolean
     * @throws
     * @description 判断 member 元素是否是集合 key 的成员
     * @author 吴杰峰
     * @date 2019/4/16
     */
    @PostMapping("/isMember")
    public boolean isMember(@RequestParam("key") String key,@RequestParam("value") String value) {
        try {
            return redisTemplate.opsForSet().isMember(key,value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key,value
     * @return boolean
     * @throws
     * @description 向redis集合(Set)中,添加一个元素
     * @author 吴杰峰
     * @date 2019/4/16
     */
    @PostMapping("/addMember")
    public boolean addMember(@RequestParam("key") String key,@RequestParam("memeber") String memeber) {
        try {
            redisTemplate.opsForSet().add(key,memeber);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Redis Set结合添加元素发生异常,key:"+key+",members:"+memeber+",ErrMsg:"+e.getMessage());
            return false;
        }
    }

    //===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束  0到 -1代表所有值
     * @return
     */
    @PostMapping("/lGet")
    public List<String> lGet(@RequestParam("key") String key,@RequestParam("start") long start,@RequestParam("end") long end) {
        try {
            List<Object> range = redisTemplate.opsForList().range(key, start, end);
            List<String> resultList = new ArrayList<>();
            for (int i = 0; i < range.size(); i++) {
                String item = String.valueOf(range.get(i));
                resultList.add(item);
            }
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    @PostMapping("/lGetListSize")
    public long lGetListSize(@RequestParam("key")String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    @PostMapping("/lGetIndex")
    public Object lGetIndex(@RequestParam("key") String key,@RequestParam("index") long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    @PostMapping("/lSet")
    public boolean lSet(@RequestParam("key") String key,@RequestParam("value") Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    @PostMapping("/lSetWithTime")
    public boolean lSetWithTime(@RequestParam("key") String key,@RequestParam("value") Object value,@RequestParam("time") long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    @PostMapping("/lSetList")
    public boolean lSet(@RequestParam("key")String key,@RequestBody List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    @PostMapping("/lSetListWithTime")
    public boolean lSetList(@RequestParam("key")String key,@RequestBody List<Object> value,@RequestParam("time") long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    @PostMapping("/lUpdateIndex")
    public boolean lUpdateIndex(@RequestParam("key") String key,@RequestParam("index") long index,@RequestParam("value") Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    @PostMapping("/lRemove")
    public long lRemove(@RequestParam("key") String key,@RequestParam("count") long count,@RequestParam("value") Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key,count,value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}

3.4. redis 配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * @描述
 * @创建人 梁XL
 * @创建时间 2019/4/15
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 选择redis作为默认缓存工具
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager rcm = RedisCacheManager.create(connectionFactory);
        return rcm;
    }

    /**
     * retemplate相关配置
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

3.5. 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class RedisDemoApplication {

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

}

4. reids 服务调用项目
4.1. pom.xml

<properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <spring-cloud.version>Finchley.RELEASEspring-cloud.version>
    properties>

    <dependencies>

        <dependency>
            <groupId>com.hiteamtechgroupId>
            <artifactId>redis_demoartifactId>
            <version>0.0.1-SNAPSHOTversion>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

    dependencies>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <repositories>
        <repository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://repo.spring.io/milestoneurl>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
        repository>
    repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

4.2. application.yml

server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka/

4.3. 使用Feign代理接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @描述
 * @创建人 梁XL
 * @创建时间 2019/4/11
 */
@Component
@FeignClient(value = "service-redis")
public interface IRedisService {

    /**
     * 读取缓存
     * @param key
     * @return
     */
    @GetMapping("/redis/get")
    String get(@RequestParam("key") final String key);

    /**
     * @description 设置缓存
     * @author 梁XL
     * @date 2019/4/10
     * @param key
     * @param value
     * @return boolean
     * @throws
     */
    @GetMapping("/redis/set")
    boolean set(@RequestParam("key") final String key,@RequestParam("value") final String value);

    /**
     * @description 写入缓存带失效时间
     * @author 梁XL
     * @date 2019/4/10
     * @param key
     * @param value
     * @param timeOut
     * @return boolean
     * @throws
     */
    @GetMapping("/redis/setWithTime")
    boolean setWithTime(@RequestParam("key") final String key,@RequestParam("value") final String value,@RequestParam("timeOut") final long timeOut) ;


    /**
     * 更新缓存
     */
    @GetMapping("/redis/update")
    boolean getAndSet(@RequestParam("key") final String key,@RequestParam("value") final String value);

    /**
     * 删除缓存
     */
    @GetMapping("/redis/delete")
    boolean delete(@RequestParam("key") final String key);

}

4.4. 跨项目调用redis

import com.hiteamtech.redis_demo.config.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @描述
 * @创建人 梁XL
 * @创建时间 2019/4/10
 */
@RestController
public class RedisTest {

    @Autowired
    private IRedisService redisService;

    /**
     * 读取缓存
     * @param key
     * @return
     */
    @GetMapping("/get")
    public String get(String key){
        return redisService.get(key);
    }

    /**
     * @description 设置缓存
     * @author 梁XL
     * @date 2019/4/10
     * @param key
     * @param value
     * @return boolean
     * @throws
     */
    @GetMapping("/set")
    public boolean set(String key, String value){
        return redisService.set(key,value);
    }

    /**
     * @description 写入缓存带失效时间
     * @author 梁XL
     * @date 2019/4/10
     * @param key
     * @param value
     * @param timeOut
     * @return boolean
     * @throws
     */
    @GetMapping("/setWithTime")
    public boolean setWithTime(String key, String value,long timeOut) {
        return redisService.setWithTime(key,value,timeOut);
    }


    /**
     * 更新缓存
     */
    @GetMapping("/update")
    public boolean getAndSet(String key, String value){
        return redisService.getAndSet(key,value);
    }

    /**
     * 删除缓存
     */
    @GetMapping("/delete")
    public boolean delete(String key){
        return redisService.delete(key);
    }

}

4.5. 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients(value = "扫描包")
public class RedisTestApplication {

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

}

5. 写在后面

这个时候打开浏览器输入 http://localhost:80/get?key=aaa 你会发现:哼,解决了。

你可能感兴趣的:(后端,框架)