在SpringBoot⼯程连接Redis

2022-01-09  本文已影响0人  天马行空_9f6e

Spring Data Redis依赖中,提供了⽤于连接redis的客户端:

RedisTemplate

StringRedisTemplate

创建springBoot应⽤

或者可以在现有的SpringBoot项目的Maven中引入

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

配置redis

application.yml⽂件配置redis的连接信息

spring:

    redis:

        host: 47.96.11.185

        port: 6379

        database: 0

        password: 123456

使⽤redis客户端连接redis

直接在service中注⼊ RedisTemplate 或者 StringRedisTemplate ,就可以使⽤此对象完成redis操作

@Service

public class ProductServiceImpl implements ProductService {

    @Autowired

    private StringRedisTemplate stringRedisTemplate;

    public void addInfoToRedis() {

        try {

            Product product =new Product("103","王老吉",4.0);

            String s =new ObjectMapper().writeValueAsString(product);

            stringRedisTemplate.boundValueOps(product.getProductId()).set(s);

         }catch (JsonProcessingException e) {

            e.printStackTrace();

        }

    }

    public Product getInfoFromRedis(String productId) {

        Product product =null;

        try {

            String s =stringRedisTemplate.boundValueOps(productId).get();

            product =new ObjectMapper().readValue(s,Product.class);

        }catch (JsonProcessingException e) {

            e.printStackTrace();

        }

        return product;

    }

}

上一篇 下一篇

猜你喜欢

热点阅读