SpringBoot整合Redis的兩種方式

SpringBoot整合Redis的兩種方式

  • 通過註解的方式
引入依賴
 <dependency>
    <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
   </dependency>

   <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
</dependency>
配置redis連接
#配置Redis服務器屬性
spring.redis.host=localhost
spring.redis.port=6379
#配置連接超時時間(毫秒)
spring.redis.timeout=3000
#配置連接池屬性
#連接池最大的鏈接數
spring.redis.jedis.pool.max-active=20
#連接池的最大空閒鏈接
spring.redis.jedis.pool.max-idle=20
#連接池的最小空閒連接
spring.redis.jedis.pool.min-idle=5
#連接池的最大等待時間
spring.redis.jedis.pool.max-wait=3000
#緩存名稱,一般會作爲緩存在業務上的分類,以key的前綴出現(userCache::)
spring.cache.cache-names=userCache
#禁用緩存前綴
#spring.cache.redis.use-key-prefix=false
#緩存超時時間
spring.cache.redis.time-to-live=120000

1.開啓使用緩存
@SpringBootApplication
@EnableCaching
public class DemoredisApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoredisApplication.class, args);
    }

}
在service或者dao層中使用緩存
/**
 * @Auther: ZQB
 * Date:2020/1/16
 */
@Service
public class CacheServiceImpl implements CacheService {
    @Resource
    private UserMapper userMapper;
    @Override
    @CachePut(value = "userCache", key = "'user:' + #result.id")
    public User saveUser(User user) {
       return userMapper.adduser(user);
    }

    @Override
    @Cacheable(value = "userCache", key = "'user:' + #id", unless = "#result == null")
    public User getUser(Integer id) {
        System.out.println("沒有命中緩存,進入業務方法了");
        return userMapper.findUserById(id);
    }

    @Override
    @CachePut(value = "userCache", key = "'user:' + #result.id", condition = "#result != null")
    public User updateUser(User user) {
        User u = this.getUser(user.getId());
        if (u == null) {
            return null;
        }
       return userMapper.updateUser(user);
    }
    @Override
    @CacheEvict(value = "userCache", key = "'user:' + #id", beforeInvocation = true)
    public void removeUser(Integer id) {
       userMapper.deleteUserById(id);
    }

}

參考鏈接: https://segmentfault.com/a/1190000017057950.

發佈了22 篇原創文章 · 獲贊 6 · 訪問量 676
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章