java web 之springboot教程(十五)----整合redis

1,下载redis,启动;

2,导入依赖包:

<!--引入 spring-boot-starter-data-redis(1.4版本后)多了个data加个红和粗吧-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

3,application.yml配置:

spring:
# Redis 配置信息
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
#    password:
    timeout: 3000
    jedis:
      pool:
        max-active: 200
        max-wait: 1000
        max-idle: 500
        min-idle: 50

4,在com.cx.springbootdemo.core下配置RedisConfiguration.java:

package com.cx.springbootdemo.core;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

@Configuration
public class RedisConfiguration {

    @Bean
    @ConditionalOnMissingBean(name="redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException{
        RedisTemplate<Object, Object> template = new RedisTemplate<Object,Object>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}

5,在com.cx.springbootdemo.pojo中的User.java序列化:

package com.cx.springbootdemo.pojo;

import java.io.Serializable;
import java.util.Date;

//@Component
//@ConfigurationProperties(prefix = "test.user")
public class User implements Serializable {

    private int id;
    private String username;
    private int age;
    private Date ctm;

    public User() {
    }

    public User(String username, int age) {
        this.username = username;
        this.age = age;
        this.ctm = new Date();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getCtm() {
        return ctm;
    }

    public void setCtm(Date ctm) {
        this.ctm = ctm;
    }
}

6,测试类SpringbootdemoApplicationTests.java:

package com.cx.springbootdemo;

import com.cx.springbootdemo.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootdemoApplicationTests {
//
//	@Autowired
//	private MemCachedClient memCachedClient;


//    @Autowired
//    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

	@Test
	public void contextLoads(){
//		// 放入缓存
//		boolean flag = memCachedClient.set("a", 1);
//
//		// 取出缓存
//		Object a = memCachedClient.get("a");
//		System.out.println(a);
//
//
//		// 3s后过期
//		memCachedClient.set("b", "2", new Date(3000));
//		Object b = memCachedClient.get("b");
//		System.out.println(b);
//
//		Thread.sleep(3000);
//		b = memCachedClient.get("b");
//        System.out.println(a);
//		System.out.println(b);

        // 存取字符串
        redisTemplate.opsForValue().set("a", "1");
        Object a = redisTemplate.opsForValue().get("a");
        System.out.println(a);

        // 存取user对象
        redisTemplate.opsForValue().set("user1", new User("张三",1 ));
        User user1 = (User) redisTemplate.opsForValue().get("user1");
        System.out.println(user1);
	}

}

测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis-Plus和Redis可以通过以下步骤实现: 1. 添加依赖:在pom.xml文件中添加Spring Boot、MyBatis-Plus和Redis的依赖。 ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置数据源:在application.properties或application.yml中配置数据库连接信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 3. 配置MyBatis-Plus:创建一个配置类,使用@MapperScan注解指定Mapper接口的扫描路径。 ```java @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ``` 4. 创建实体类和Mapper接口:创建实体类和对应的Mapper接口,使用注解进行映射。 ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; } ``` ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 添加Redis配置:在application.properties或application.yml中配置Redis连接信息。 ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 6. 编写业务逻辑:创建Service类,注入Mapper和RedisTemplate,并编写业务逻辑。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public User getUserById(Long id) { // 先从缓存中获取数据 String key = "user:" + id; User user = (User) redisTemplate.opsForValue().get(key); // 如果缓存中不存在,则从数据库中获取数据 if (user == null) { user = userMapper.selectById(id); // 将数据存入缓存 redisTemplate.opsForValue().set(key, user); } return user; } } ``` 这样,你就成功地将Spring Boot、MyBatis-Plus和Redis进行了整合。通过MyBatis-Plus进行数据库操作,并通过Redis进行缓存,提高系统性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值