一、spring微服务接入redis

注:本文只将快速应用,深入了解会另开文章

一、启用redis服务

https://github.com/tporadowski/redis/releases
解压即可使用:
在这里插入图片描述

  1. 双击 redis-server.exe 启动redis服务端
  2. 修改默认配置文件 redis.windows.conf(左为默认,右为修改后)
    在这里插入图片描述
  3. 双击 redis-cli.exe 启动redis客户端
  4. 验证方式如下图
    在这里插入图片描述

二、项目接入redis

pom依赖

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- jedis连接池 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

配置文件

.yml

# 项目通用配置
spring:
  redis:
    host: localhost
    port: 6379
    database: 12
#sso配置
sso:
  redis:
    host: localhost
    port: 6379
    database: 12

redis个性化配置

package com.springboot.demo.properties;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

@Setter
@Getter
@ToString
@Component
@ConfigurationProperties(prefix = "sso.redis")  //  通过注解读取sso.redis开头的配置文件
public class RedisProperty {
    private Integer database;

    @Value("${sso.redis.cluster.nodes:#{null}}")
    private List<String> nodes;

    private String host;

    private Integer port;

    private String password;

    private Pool pool = new Pool();

    /**
     * Pool properties.
     */
    @Data
    public static class Pool {

        /**
         * Maximum number of "idle" connections in the pool. Use a negative value to
         * indicate an unlimited number of idle connections.
         */
        private int maxIdle = 50;

        /**
         * Target for the minimum number of idle connections to maintain in the pool. This
         * setting only has an effect if it is positive.
         */
        private int minIdle = 10;

        /**
         * Maximum number of connections that can be allocated by the pool at a given
         * time. Use a negative value for no limit.
         */
        private int maxActive = 200;

        /**
         * Maximum amount of time a connection allocation should block before throwing an
         * exception when the pool is exhausted. Use a negative value to block
         * indefinitely.
         */
        private Duration maxWait = Duration.ofMillis(3000);

        private int timeout = 5000;
    }
}

连接池与连接工厂实现

package com.springboot.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.demo.properties.RedisProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

@Configuration(value = "ssoRedisConfig")
public class RedisConfig {

    @Autowired
    private RedisProperty redis;

    /**
     * 为RedisTemplate配置Redis连接工厂实现
     * LettuceConnectionFactory实现了RedisConnectionFactory接口
     *
     * @return 返回LettuceConnectionFactory
     */
    public RedisConnectionFactory ssoRedisConnectionFactory() {
        //ClientResources clientResources = DefaultClientResources.create();
        JedisConnectionFactory factory;
        if (redis.getNodes() != null) {
            final RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(redis.getNodes());
            if (StringUtils.hasText(redis.getPassword())) {
                clusterConfiguration.setPassword(RedisPassword.of(redis.getPassword()));
            }
            factory = new JedisConnectionFactory(clusterConfiguration, getJedisPoolConfig());
        } else {
            final RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration(redis.getHost(), redis.getPort());
            if (StringUtils.hasText(redis.getPassword())) {
                standaloneConfiguration.setPassword(RedisPassword.of(redis.getPassword()));
            }
            standaloneConfiguration.setDatabase(redis.getDatabase());
            factory = new JedisConnectionFactory(standaloneConfiguration);
        }
        factory.afterPropertiesSet();
        return factory;
    }

    /**
     * 配置RedisTemplate
     * 【Redis配置最终一步】
     *
     * @return 返回一个可以使用的RedisTemplate实例
     */
    @Bean(name = "ssoRedisTemplate")
    public RedisTemplate<String, Object> ssoRedisTemplate(){
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(ssoRedisConnectionFactory());
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 读取Jedis连接池配置
     * @return
     */
    public JedisPoolConfig getJedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(redis.getPool().getMinIdle());
        jedisPoolConfig.setMaxIdle(redis.getPool().getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redis.getPool().getMaxWait().toMillis());
        jedisPoolConfig.setMaxTotal(redis.getPool().getMaxActive());
        //逐出连接的最小空闲时间,默认为180000毫秒(30分钟)
        jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);
        //对象空闲多久后逐出,当空闲时间>该值,且 空闲连接>最大空闲连接数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断
        jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(60000);
        //逐出扫描的时间间隔(毫秒)如果为负数,则不运行逐出线程,默认为-1
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(60000);
        return jedisPoolConfig;
    }

}

代码验证

package com.springboot.demo.domin.hello.controller;

import com.springboot.demo.annotation.sysLog.aspect.SysLog;
import com.springboot.demo.domin.hello.service.HelloService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/v1/test")
@Api(value = "HelloSpringBoot", tags = "测试", description = "我看行")
public class HelloSpringBoot {

    @Autowired
    HelloService helloService;

    @SysLog("redis 测试")
    @GetMapping(value = "/redis")
    public String testRedis(@RequestParam("str") String str){
        return helloService.testRedis(str);
    }
}

package com.springboot.demo.domin.hello.service.impl;

import com.springboot.demo.domin.hello.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class HelloServiceImpl implements HelloService {

    @Autowired
    @Qualifier(value = "ssoRedisTemplate")
    private RedisTemplate redisTemplate;

    @Value(value = "#{T(java.lang.Integer).parseInt('${sso.forgot_verify_code_effect_mins:5}')}")
    private Integer verifyCodeEffectMins;

    @Override
    public String testRedis(String str) {

        //将生成的随机码存储到Redis中
        redisTemplate.opsForValue().set(str, "abc", verifyCodeEffectMins, TimeUnit.MINUTES);
        return redisTemplate.opsForValue().get(str).toString();
    }

}

三、启动项目,页面访问

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值