• SpringBoot整合Redis


    1.引入maven依赖
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    </dependency>
    2.在application.properties里面配置地址
    spring.redis.host=192.168.3.4
    spring.redis.port=6379
    spring.redis.database=0
    3.在config文件中配置RedisConfig
    import com.hourui.util.RedisUtil;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class RedisConfig {
    
        //读取配置文件中的redis的ip地址
        @Value("${spring.redis.host:disabled}")
        private String host;
    
        @Value("${spring.redis.port:0}")
        private int port;
    
        @Value("${spring.redis.database:0}")
        private int database;
    
        @Bean
        public RedisUtil getRedisUtil() {
            if (host.equals("disabled")) {
                return null;
            }
            RedisUtil redisUtil = new RedisUtil();
            redisUtil.initPool(host, port, database);
            return redisUtil;
        }
    }
    4.在util文件中配置RedisUtil
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    public class RedisUtil {
    
        private JedisPool jedisPool;
    
        public void initPool(String host,int port ,int database){
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(200);
            poolConfig.setMaxIdle(30);
            poolConfig.setBlockWhenExhausted(true);
            poolConfig.setMaxWaitMillis(10*1000);
            poolConfig.setTestOnBorrow(true);
            jedisPool=new JedisPool(poolConfig,host,port,20*1000);
        }
    
        public Jedis getJedis(){
            Jedis jedis = jedisPool.getResource();
            return jedis;
        }
    
    }
    
    
    5.注入RedisUtil,然后使用
    @Service
    public class CartServiceImpl implements CartService {
    
        @Autowired
        RedisUtil redisUtil;
    
        @Override
        public void addCart(OmsCartItem omsCartItem) {
    
            cartItemMapper.insertSelective(omsCartItem);
    
            // 同步redis缓存
            Jedis jedis = redisUtil.getJedis();
    
            jedis.hset("user:"+omsCartItem.getMemberId()+":cart",omsCartItem.getId(), JSON.toJSONString(omsCartItem));
    
            jedis.close();
    
        }
    } 
  • 相关阅读:
    ios7.0结合storyborad实现页面跳转的总结
    ios上取得设备唯一标志的解决方案
    【iOS】Objective-C简约而不简单的单例模式
    ios应用启动后的自动版本检测方式
    linux安装常用软件和查询基本信息
    配置本地yum仓库
    RedHat 6.5 上将系统语言修改为中文
    RedHat7.4配置yum网络源
    linux环境中,两个不同网段的机器互通
    redhat 配置eth0网卡
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/12057763.html
Copyright © 2020-2023  润新知