springboot-redist

个人感觉:之前一直使用的是ssm框架觉得很好用,直到学习了springboot的之后就觉得之前的配置太复杂了,这篇文章呢就介绍下springboot和redis摩擦出的火花

首先新建一个springboot的项目

在pom.ml文件中添加依赖

    <dependency>
          <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.2.RELEASE</version>
        </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
    <exclusions>
    <exclusion>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  </exclusion>
  <exclusion>
  <groupId>io.lettuce</groupId>
  <artifactId>lettuce-core</artifactId>
  </exclusion>
  </exclusions>
    </dependency>

<!-- 添加jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

<!--spring2.0集成redis所需common-pool2-->
<!-- 必须加上,jedis依赖此 -->
<!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>

<!-- 将作为Redis对象序列化器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>

 

在配置yml文件中

spring:
  redis:
  #链接redis的地址
    host: 127.0.0.0
    #端口号
    port: 6379
  password:
    jedis:
      pool:
      #连接池最大连接数
        max-active: 8
        #连接池最大等待时间
        max-wait: -1
    #连接池最大链接时间
    timeout: 0
    #数据库索引(默认为0)
    database: 0

 

Redis自定义的配置(之前使用的ssm是在xml文件中配置redis的 现在给大家分享一下在java类中配置)

新建一个RedisConfiguration类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis 配置类
 */
@Configuration
// 必须加,使配置生效
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * Logger
     */
    private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);

    
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        //  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
        // 使用:进行分割,可以很多显示出层级关系
        // 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":");
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(":" + String.valueOf(obj));
            }
            String rsToUse = String.valueOf(sb);
            lg.info("自动生成Redis Key -> [{}]", rsToUse);
            return rsToUse;
        };
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
        lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .RedisCacheManagerBuilder
                .fromConnectionFactory(jedisConnectionFactory);
        return builder.build();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
        //设置序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
        redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Override
    @Bean
    public CacheErrorHandler errorHandler() {
        // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
        lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
        CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
            @Override
            public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
                lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
            }

            @Override
            public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
                lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
            }

            @Override
            public void handleCacheEvictError(RuntimeException e, Cache cache, Object key)    {
                lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
            }

            @Override
            public void handleCacheClearError(RuntimeException e, Cache cache) {
                lg.error("Redis occur handleCacheClearError:", e);
            }
        };
        return cacheErrorHandler;
    }

    /**
     * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
     * 不了解的同学可以去看@ConfigurationProperties和@Value的作用
     *
     */
    @ConfigurationProperties
    class DataJedisProperties{
        @Value("${spring.redis.host}")
        private  String host;
        @Value("${spring.redis.password}")
        private  String password;
        @Value("${spring.redis.port}")
        private  int port;
        @Value("${spring.redis.timeout}")
        private  int timeout;
        @Value("${spring.redis.jedis.pool.max-idle}")
        private int maxIdle;
        @Value("${spring.redis.jedis.pool.max-wait}")
        private long maxWaitMillis;

        @Bean
        JedisConnectionFactory jedisConnectionFactory() {
            lg.info("Create JedisConnectionFactory successful");
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setHostName(host);
            factory.setPort(port);
            factory.setTimeout(timeout);
            factory.setPassword(password);
            return factory;
        }
        @Bean
        public JedisPool redisPoolFactory() {
            lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

            JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
            return jedisPool;
        }
    }

}

 

业务层代码(其他代码就贴了 dao层和实体类都是一些简单的增删改查,和getter和setter

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cherry.framework.dao.UserEntityMapper;
import com.cherry.framework.model.UserEntity;
import com.cherry.framework.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * User ServiceImpl
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserEntityMapper userEntityMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 新增
     *
     * @param userEntity
     * @return
     */
    @Override
    @Transactional
    public int save(UserEntity userEntity) {
        userEntityMapper.insert(userEntity);
        return userEntity.getUserId();
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public PageInfo<UserEntity> findAllUserList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserEntity> list = userEntityMapper.selectAll();
        PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
        // 具体使用
        redisTemplate.opsForList().leftPush("user:list", JSON.toJSONString(list));
        stringRedisTemplate.opsForValue().set("user:name", "张三");
        return pageInfo;
    }
}

contorller层(注入service)

 @RequestMapping(value = "/user/list")
      public PageInfo<UserEntity> findUserList(int pageNum, int pageSize) {
          PageInfo<UserEntity> pageInfo = userService.findAllUserList(pageNum, pageSize);
          return pageInfo;
      }

访问相应的路径 (此篇文章 主要用于学习笔记^ ^)

 

转载于:https://www.cnblogs.com/blackCatFish/p/9927644.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: vc-redist.x64是微软的运行库,用于支持不同的应用程序在64位操作系统上正常运行。VC指的是Visual C++,是微软的一种编程语言和开发环境。 在开发和运行基于Visual C++编写的应用程序时,需要安装相应版本的vc-redist.x64以保证程序的正常运行。这是因为应用程序在编译时使用了Visual C++的库文件,而这些库文件在目标机器上可能没有或者版本不匹配。 通过安装vc-redist.x64,可以确保运行Visual C++程序所需的库文件被正确地部署到系统中,从而避免程序因缺少库文件而无法运行或出现错误的情况。可以将vc-redist.x64视为一个桥梁,将程序所需的库文件与系统进行连接和匹配。 需要注意的是,不同版本的Visual C++编译的程序所需的vc-redist.x64版本是不同的。因此,在安装应用程序时,需要根据开发者提供的要求来选择相应的vc-redist.x64版本。 总之,vc-redist.x64是微软提供的运行库,用于支持64位操作系统上运行基于Visual C++编写的应用程序。安装正确的vc-redist.x64版本是保证应用程序正常运行的关键。 ### 回答2: vc-redist.x64 是一个用于安装并配置 Microsoft Visual C++ Redistributable 的程序包。Microsoft Visual C++ Redistributable 是 Microsoft 公司为了支持运行使用 C++ 开发的应用程序而提供的运行库。vc-redist.x64 是针对 64 位操作系统的版本。通过安装 vc-redist.x64,可以确保您的计算机上有所需的 Visual C++ 运行时组件,以便正确运行依赖于这些组件的应用程序。 Visual C++ Redistributable 是一些动态链接库(DLL)文件的集合,这些文件包含了 Visual C++ 编译器生成的代码的运行时支持。这些组件被许多软件和游戏使用,因此安装了 vc-redist.x64 是非常重要的。如果缺少这些组件,则可能会导致应用程序崩溃、错误或无法正常运行。 在安装 vc-redist.x64 时,可能会弹出一个安装向导,您只需按照步骤进行操作,等待安装完成即可。安装完成后,您的计算机将拥有所有必需的 Visual C++ 运行时组件,并且可以支持所需的应用程序。在某些情况下,如果您安装了多个版本的 Visual C++ Redistributable,可能会存在冲突问题。这时,您可以尝试通过卸载冲突的版本或重新安装 vc-redist.x64 来解决。 总之,vc-redist.x64 是用于安装和配置 Microsoft Visual C++ Redistributable 的程序包。它是确保您计算机能够正确运行依赖于 Visual C++ 的应用程序的重要组件,因此在需要时安装它是非常必要的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值